0

I want to make a php search query.
First put a sentence and explode every word get $name.
Then I put $name make a query to match all the name which exist in my database.
How to use a if ($num_results > 0) if I am not sure how many $name are matched and echo out? (may be $row['name'] is null, maybe $row['name'] is 1 or 2, I want to get them one by one)

$query = mysql_query("SELECT * FROM books 
  WHERE name LIKE '$name[0]' OR name LIKE '$name[1]' OR name LIKE '$name[2]' 
        OR name like '$name[3]' ");
while ($row = mysql_fetch_array($query)) {
  if ($num_results > 0) {
    echo $row['name'][0] ;
  }
  if ($num_results > 1) {
    echo $row['name'][1] ;
  }
  if ($num_results > 2) {
    echo $row['name'][2] ;
  }
  if ($num_results > 3) {
    echo $row['name'][3] ;
  }
}

3 Answers 3

4

use:

mysql_num_rows($query);

to get the amount of rows you get from your mysql query

<?php if (mysql_num_rows($query)>0){?>
Do stuff
<? }else{ ?>
We didn't find anything!
<?php }?>
Sign up to request clarification or add additional context in comments.

Comments

2

How about:

$i = 0
while($row = mysql_fetch_array($query)) {
    echo $row['name'][$i];
    $i++;
}

Comments

1

I didn't actually understood what you really want but your code should make more sense like this:

<?php
$searchphrase="alex nick george";
// this:
$names = explode(" ",$searchphrase);
// produces the following:
$names = array("alex","nick","george");
// so you can make the query:
if(is_array($names)){
    $query = "SELECT * FROM books WHERE name IN ('".implode(",",$names)."') ORDER BY FIELD (name,".implode(",",$names).")";
    $result = mysql_query($query) or die(mysql_error());
    if (mysql_num_rows($result) == 0){
        // no results
    }else{
        while ($row = mysql_fetch_array($result)) {
            echo $row['name'];
        }
    }
}
?>

Perhaps if you describe it better we can help more efficiently.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.