Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php select * where like

Hi I am trying to get a search working for a site. It has 2 inputs for taking in info, one is a dropdown.

<div id="search">
<form action="projectsearchall.php" method="post" enctype="multipart/form-data">
<h3>Search for an Item</h3>

<p>Keywords</p><p><input name="keywords" type="text" value="keywords"></p>


<p>Select A Location</p><p>

<select name="location" id="jumpMenu">
 <option>Any Location</option>
 <option>Antrim</option>
 <option>Armagh</option>
 <option>Carlow</option>
 <option>Cavan</option>


</select>
</p>
<p>

</form>
</div>

I cannot seem to figure out how to combine the 2 inputs to give a result, I can do it separately, but not working together to get a more accurate result.

php

$keywords = $_POST['keywords'];
$keylocation =$_POST['location'];
$username = $_SESSION['username'];

   //MySQL Database Connect
 include 'connect.php';
 //make sql query

$result = mysqli_query($con,"SELECT * FROM projectitem where description  like '%$keywords%'  or item like '%$keywords%' or location like '%$keywords%'");

Thanks in advance!

like image 762
user1944305 Avatar asked May 07 '13 16:05

user1944305


1 Answers

I think you may do some preprocessing, before running your query.

First off, you need to give your select options some sort of value to check against.

I don't know your exact database structure, but assuming that you're working with the select texts, you may want to try this:

$query = "SELECT * FROM projectitem WHERE (description LIKE '%$keywords%' OR item LIKE '%$keywords%')";

This is your base query and running it right now will check against the keywords, but no location.

if($keylocation != "Any location") $query .= " AND location = '$keylocation'";

This last line will add the location as additional filter to your query. Run it, and see what it does. (I'm not sure about the string comparison there though)

Ah yes, as a final advice: Be sure to run your input through the escape function mysqli_escape_string. Otherwise you're opening yourself to SQL injections.

like image 76
Refugnic Eternium Avatar answered Oct 11 '22 08:10

Refugnic Eternium