Reputation: 183
i have a search function on my website where users can search for products. it works perfectly fine except for the fact that when a user searches for 'ipod' it comes up with no result as the name of the product is 'apple ipod'. how do i code it so that when part of the name of the product is searched, the correct product comes up?
my code is as follows:
<div id="search" align="right">
<form action="" method="get">
<span id="sprytextfield1">
<input name="search" id="search2" type="text" width="250px"/>
<span class="textfieldRequiredMsg"></span></span>
<input name="" type="submit" value="Search"/>
</form></div>
<br /><br />
<h2>Your Search Results For "<?php echo $_GET['search'] ?>":</h2><hr />
<table border="0" cellpadding="2px" width="600px">
<?
$search = $_GET['search'];
$result=mysql_query("select * from products WHERE name = '$search'")
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo ' '.'Could Not Be Found';
}
else {
while($row=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo'<img src="getImage.php?id=' . $row['serial'] .'"/>'
?> </td>
<td> <b><a href="pdaproduct.php?product_id=<?=$row['serial']?>"><?=$row['name']?></a></b><br />
Price:<big style="color:green">
£<?=$row['price']?></big><br /><br />
<input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
</td>
</tr>
<tr><td colspan="2"><hr size="1" /></td>
<?
}
}?>
</table>
thanks for any advice given! :)
Upvotes: 1
Views: 128
Reputation: 4145
Searching keyword in a table (eg: your product list) LIKE can be very useful but doesn't perform well on long text fields (eg: description), so consider also full text index and the MATCH () AGAINST operator.
Here mysql manual page
To avoid to return the page No results found, sorry, (after a none results query) you can use the SOUNDEX operator
mysql_query("select * from products WHERE SOUNDEX(name) > 0 ORDER BY SOUNDEX(name) DESC" ):
Here mysql soundex manual page
Upvotes: 0
Reputation: 30131
You can use a LIKE
statement, like so
select * from products WHERE name LIKE '%$search%'
The above will match both 'apple ipod', 'ipod' and 'apple ipod'
Upvotes: 2
Reputation: 29985
Ignoring the fact that your code should never be used for production (it's unsafe), you should use a LIKE
in your query.
mysql_query("select * from products WHERE name LIKE '%$search%'")
Now, optimized against SQL injections and other things you don't want, this would become:
mysql_query("select * from products WHERE name LIKE '%".mysql_real_escape_string($search)."%'")
Upvotes: 2