ron ron - 1 year ago 59
MySQL Question

Display all related data when searchkeyword

This is part of my php file.

if(preg_match("/^[ a-zA-Z]+/", $_POST['searchName']))

$con=mysql_connect ("localhost", "root", "");


$result=mysql_query("SELECT Name, Price FROM info WHERE Name='$name'");

echo $row['Name'];
echo $row['Price'];
echo "<p>Please enter a search query</p>";

The problem for me now is for example I want to search for chicken pizza but it will only display the information when I type to full sentence which is chicken pizza. How can I make if I type chicken or other keyword and it will display to corresponding data related to chicken like chicken pie, chicken wings? Thanks for advicing.

Note:I will change it to mysqli after I solved this problem

Answer Source

You need to use the LIKE operator here. LIKE comes with varieties of ways. You can use % before the keyword, after the keyword, and both before and after the keyword.


"SELECT Name, Price FROM info WHERE Name LIKE '%$name%'"

Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern.

And Stop using mysql_*, start with mysqli_* OR PDO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download