简体   繁体   中英

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>

在此处输入图片说明

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.

您好像缺少$之前numrows上这一行:

if(numrows > 0){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM