AJ Riley AJ Riley - 1 year ago 71
PHP Question

PHP searching database with same name but different sizes

Basically I have a search function

in my database I have

  • Macbook Air 13.3 Inch

  • Macbook Air 11.6 Inch

  • Macbook Pro 13.3 Inch

My keywords are

  • macbook air 13.3 13 inch

  • macbook air 11.6 11 inch

  • macbook pro 13.3 13 Inch

The issue

When I search macbook it shows all 3 which is correct, but when I search macbook pro it still shows the macbook airs as well. The same thing happens when I search macbook air 13.3 inch it still shows all 3 macbooks.

here is the code

$condition = '';
$query = explode(" ", $_GET["search"]);
foreach($query as $text)
$condition .= "keywords LIKE '%".mysqli_real_escape_string($connect, $text)."%' OR ";
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM products WHERE " . $condition;
$result = mysqli_query($connect, $sql_query);
if(mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$metadata = $row['metadata'];

echo '<label>Data not Found</label>';

When I search Macbook air 13.3 inch I want it to just show the macbook air that is the 13.3 inch..

Answer Source

You're using OR in your SQL statement, you probably meant it to be an AND.

As of now you're searching for 'Macbook' OR 'air' OR 'pro' etc. which comes up with everything that has one of these keywords in them.

Use AND for this; It'll search for something in your DB which uses all the keywords you assign in your loop. it'll be searching for 'Macbook' AND 'air' instead of them seperate.

so instead of:

foreach($query as $text) {
  $condition .= "keywords LIKE '%".mysqli_real_escape_string($connect,     $text)."%' OR ";


foreach($query as $text) {
  $condition .= "keywords LIKE '%".mysqli_real_escape_string($connect,     $text)."%' AND";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download