无法从mysql数据库中检索数据

时间:2013-11-10 15:36:50

标签: php html mysql

我从教科书中学习了一些php-mysql教程。我应该能够从“书籍”数据库中检索一些数据,例如,如果我选择作者作为searchtype而迈克尔作为searchterm,我应该得到一些结果,因为作者名称在数据库中。但是,在我从表单提交数据后,我没有得到任何结果。它只是显示以下内容:

Searh Results 

Number of books found:

follwing是我的表格的html代码:

<html>
<head>
<title> Catalog Search</title>
</head>
<body>
<h1>Catalog Search</h1>
<form action="results.php" method="post">
Choose Search Type:<br />
<select name="searchtype">
<option value="author">Author</option>
<option value="title">Title</option>
<option value="isbn">ISBN</option>
</select>
<br />
Enter Search Term:<br />
<input name="searchterm" type="text">
<br />
<input type="submit" value="Search">
</form>
</body>
</html>

我有一个名为books的数据库和一个名为results.php的PHP脚本:

<html>
<head>
<title>Search Results</title>
</head>
<body>
<h1>Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST["searchtype"];
$searchterm=$_POST["searchterm"];
if (!$searchtype || !$searchterm)
{
echo 'You have not entered search details.
 Please go back and try again.';
exit;
}

$searchterm= trim($searchterm);
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);

// Create connection
$con=mysqli_connect("localhost","myusername","mypassword","books");

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
echo '<p>Number of books found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = mysql_fetch_array($result);
echo '<p><strong>'.($i+1).'. Title: ';
echo htmlspecialchars(stripslashes($row['title']));
echo '</strong><br />Author: ';
echo stripslashes($row['author']);
echo '<br />ISBN: ';
echo stripslashes($row['isbn']);
echo '<br />Price: ';
echo stripslashes($row['price']);
echo '</p>';
}
?>
</body>
</html>

代码有什么问题?谢谢你提前。

1 个答案:

答案 0 :(得分:1)

您的连接使用mysqli扩展程序,因此您的查询也必须使用该扩展程序,而不是mysql_*

$result = mysql_query($query); // Wrong extension. Use mysqli

应该是

$result = mysqli_query($con,$query);

然后所有后续数据库函数都必须使用mysqli_*,你不能把它们混合在一起。

旁注: 使用 mysqli_real_escape_string 代替addslashes