Robin Smiet
Robin Smiet

Reputation: 39

Why can't my PHP search engine find any records?

I've written a piece of code but I can't seem to make it work. I do have a connection with my database. When I submit the form it goes to the else block (echo "Geen resultaat gevonden voor \"<b>$s</b>\"";)

What am I doing wrong with my code? I've also added a screenshot of my database.

<body>

        <h2> hier komt een kleine foto</h2>
        <form action='./search.php' method='get'>
            <input type='text' name='s'size='50' value='<?php echo $_GET['s']; ?>' />
            <input type='submit' value='Zoek'/>
        </form>
        <hr />
        <?php       
            $s = $_GET['s'];            
            $terms = explode (" ", $s);
            $query = "SELECT * FROM 'ID' WHERE ";

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

                if ($i ==1)
                    $query .= "keywords LIKE '%$each%' ";
                else
                    $query .= "OR keywords LIKE '%$each%' ";
            }
            //connect to database
            mysql_connect("server", "username", "password");
            mysql_select_db("database");

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

                while($row = mysql_fetch_assoc($query)){
                    $id = $row['id'];
                    $photo = $row['photo'];
                    $title = $row['title'];
                    $description = $row['description'];
                    $price = $row['price'];
                    $Link = $row['Link'];
                    $keywords = $row['keywords'];

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

            }
            else
                echo "Geen resultaat gevonden voor \"<b>$s</b>\"";

            //disconect
            mysql_close();
        ?>
</body>
</html>

enter image description here

Upvotes: 2

Views: 78

Answers (2)

Warren Sergent
Warren Sergent

Reputation: 2597

You have a couple of issues.

  • if(numrows > 0){ should be looking at $numrows
  • $query = "SELECT * FROM 'ID' WHERE " - You have wrapped your table name in single quotes. This will cause a syntax error - consider changing to backticks (`), or removing the quotes completely.
  • You shouldn't use mysql_* functions - they are deprecated for a reason. The PHP manual suggests you use mysqli_* functions or PDO instead.

The first one will fix your current problem, but the second one is far more important, and something you should look further in to.

It looks like you're fairly new to PHP and MySQL - so this is a good opportunity for you to learn it correctly.

Upvotes: 3

Daniel Lazdin
Daniel Lazdin

Reputation: 1

Looks like you've missing $ before numrows on this line:

if(numrows > 0){

Upvotes: 0

Related Questions