Search code examples
phpsearch-engine

search engine error


I seam to be getting the problem in the code below. The problems that arise are

"Notice: Undefined variable: i in C:\wamp\www\search\search.php on line 21"

and

"Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\search\search.php on line 34".

Line 21 is $i++;

Line 34 is $num_rows = mysql_num_rows($query)

<body>
    <h2>Search Engine</h2>
    <form action='./search.php' method='get'>
        <input type='text' name='k' size='50' value='<?php echo $_GET['k'] ?>' />
        <input type='submit' value='Search'/>
    </form>
    <hr />
    <?php
    $k = $_GET['k'];
    $terms = explode(" ", $k);
    $query = "SELECT * FROM search WHERE ";

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

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

    //connect
    mysql_connect("localhost", "root", "password");
    mysql_select_db("search");

    $query = mysql_query($query);
    $num_rows = mysql_num_rows($query);

    if ($num_rows > 0){

        while($row = mysql_fetch_assoc($query)){
            $id = $row['id'];
            $title = $row['title'];
            $description = $row['description'];
            $keywords = $row['Keywords'];
            $link = $row['link'];

            echo "<h2><a href='$link'>$title</a></h2>
            $description<br /><br />";
        }

    }
    else
        echo "No results found for \"<b>$k</b>\"";

    //disconnect
    mysql_close();

    ?>
</body>

Does anyone know how to fix it?


Solution

  • Error1: use of for loop:

    foreach ($terms as $each)
    {
        //....
    }
    

    or

    for($i = 0; i < count($terms); i++)
    {
        $each = $terms[i];
        //....
    }
    

    $i++ is useless in foreach

    Error2: mysql_query() will fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. so here is a sample code to fix it:

    $num_rows = 0;
    if($query){
        $num_rows = mysql_num_rows($query);
    }