-5

This is my PHP code of the "Search Box" I am going to include in my website. I am getting the following error when I try to search my database by entering keywords.

Notice: Undefined index: searchterm in C:\xampp\htdocs\abell12\search.php on line 14

...And this is the full php code

index.php

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Search (with keywords) Tutorial</title>
    </head>

    <body>
    <form action="search.php" method="POST">
        <input type="text" name="searchterm" placeholder="Search..."><br />
        <input type="submit" value="Search">
    </form>
    </body>
    </html>

search.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Search (with keywords) Tutorial</title>
</head>

<body>
<?php

mysql_connect("127.0.0.1","root","root");
mysql_select_db("dummy_info");

$search = mysql_real_escape_string($_POST['searchterm']);

$find_books = mysql_query("SELECT * FROM `listings` WHERE `title` LIKE'%$search%'");
while($row = mysql_fetch_assoc($find_books))
{
    $title = $row['title'];


    echo "$title<br />";

}

?>
</body>
</html>  
Darren
  • 3
  • 2

1 Answers1

0

You should check if $_POST['searchterm'] is set first. It will only be set when the form is submitted.

Also don't use Mysql_ functions. They are deprecated. Would advice you to use MySQLI since they have protection against SQL Injection attacks etc.

if(isset($_POST['searchterm']))
{
    $search = mysql_real_escape_string($_POST['searchterm']);

    $find_books = mysql_query("SELECT * FROM `listings` WHERE `title` LIKE '%$search%'");

    if(mysql_num_rows($find_books) > 0)
    {
        while($row = mysql_fetch_assoc($find_books))
        {
            $title = $row['title']; 
            echo "$title<br />";
        }
    }
    else
    {
        echo "No Record found";
    }
}
Kanishk Dudeja
  • 1,201
  • 3
  • 17
  • 33