hi i'm trying to create a search function for my website and I keep getting this error

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/a7526299/public_html/SearchResult.php on line 158

 <form action='SearchResult.php' method= 'get'>
 <input type='test' name='k' size='50' value='<?php echo $_GET['k']; ?>' />
 <input type='submit' value='search' />
 </form>


 <br />
 <br />

 Search Results 
 <br />
 <br />
 <br />
 <br />
<?php

$k = $_GET['k'];

$terms = explode ("  ", $k);
$query = "SELECT * FROM Products WHERE ";

foreach ($terms as $each) {
$i++;

if ($i == 1) 
     $query   .="keywords LIKE '%each%' "; 
else 
     $query   .="OR keywords LIKE '%each%' ";
}


// connect 
mysql_connect ("", "", ");
mysql_select_db("Products");

$query = mysql_query ($query);
$numrows = mysql_num_rows($query);
if ($numbers > 0) {

    while ($row = mysql_fetch_assoc($query)) 
    {
        $id= $row['id'];
        $id= $row['Brand'];
        $id= $row['Description'];
        $id= $row['Category'];
        $id= $row['Price'];
        $id= $row['Image'];

        echo "$id, $Brand $Description, $Category, $Price, $Image"; 


    }
}
else 
    echo "No results found for $k";
// disconnect 
mysql_close(); 
?>
Member Avatar for P0lT10n

First of all, on line 33 you didnt close the las " (quote) and secod, you cant do OR when using WHERE, eg:

You are doing this: SELECT * FROM Products WHERE keywords LIKE '%each%' but if you use OR because of the IF it will be like this SELECT * FROM Products WHERE OR keywords LIKE '%each%' <---- THATS THE ERROR, YOU CANT USE OR WHEN YOU NEVER USED A CLAUSE BEFORE...

My first guess is that the connection to your database is failing. you can check this by using:

mysql_error();

So on lines 33 and 34 should look like this:

mysql_connect ("", "", ") or die(mysql_error());
mysql_select_db("Products") or die(mysql_error());

This will let you know if the connection is failing, which would cause mysql_num_rows() to fail. Also, i think you mean for $numbers on line 38 to be $numrows.

Hope this helps.

Member Avatar for diafol

You should include error handling in the script like an or die() thingy - see the php manual for setting up conenctions and selecting dbs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.