这是"搜索框"的PHP代码。我将在我的网站上加入。当我尝试通过输入关键字搜索我的数据库时出现以下错误。
注意:未定义的索引:第14行的C:\ xampp \ htdocs \ abell12 \ search.php中的searchterm
...这是完整的PHP代码
的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>
答案 0 :(得分:0)
您应该先检查是否设置了$ _POST ['searchterm']。只有在提交表单时才会设置它。
也不要使用Mysql_函数。它们已被弃用。建议您使用MySQLI,因为它们可以防止SQL注入攻击等。
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";
}
}