Jump to content

help with LIKE code, for a very simple search feature


therelelogo

Recommended Posts

Hi,

 

I'm a little confused with implementing a search feature to my site. Here is my search box

 

<form action="search_results.php" method="post" name="search">
		<input name="search_term" style="width: 312px" type="text" />
		<select name="catsearch" style="width: 188px">
  	  <option selected="selected">All Categories</option>
  <option>Baby & Kids</option>
  <option>Clothing</option>
  <option>Collectables</option>
  <option>Computers & Accessories</option>
  <option>DVD & Film</option>
  <option>Furniture</option>
  <option>Novelty & Unusual</option>
  <option>Services</option>
  <option>Everything Else</option>
  </select><input name="search" type="submit" value="Search" /></form>

 

i'm just wanting to focus on the actual "search_term" input box for the time being, we can forget the drop down box. So when a user types something in and clicks "search" it takes them to this page:

 

$result = mysql_query("SELECT * FROM adverts WHERE item_name LIKE '{$_GET['search_term']}'")   
or die(mysql_error());  

echo "<table border='0'>";
echo "<tr> <th></th> <th>Price</th> <th>Seller</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>"; 
echo $row[printf('<img src="%s" height="96" width="128" style="border: 0" />', $row['image_location'])];
echo "</td><td>"; 
echo "<a href=\"view_advert_specific.php?id=$row[item_id]\">". $row['item_name'] . "</a>";
echo "</td><td>";
echo $row['item_price'];
echo "</td><td>"; 
echo $row['seller'];
echo "</td></tr>"; 


} 

echo "</table>";
?>

 

NOTE: yes i do have the connection info there, and all columns and table names are correct because I have reused more or less the same code over and over with no problems.

 

However the code either returns nothing, or returns everything (i fiddle about with it alot), is there any straightforward method to getting something like this to work? I mean is it not just like searching a table for a field that looks LIKE whatever was typed? or is that just wishful thinking?

 

Thanks in advance

 

Apart from changing GET to POST, you should also think about escaping data coming from the form.

 

$searchTerm = mysql_real_escape_string($_POST['search_term']);
$result = mysql_query("SELECT * FROM adverts WHERE item_name LIKE '%$searchTerm%'")   
or die(mysql_error());  

 

This is to protect you from SQL injections.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.