PHP没有返回mysql结果

时间:2016-11-10 15:38:57

标签: php html mysql mysqli

我是PHP的新手,或者一般的数据库编程。对于一个项目,我必须在书店数据库中查询书籍信息(一个非常小的数据库)并在下一页上显示它。以下是我的书店搜索页面的代码:

<?php
 $con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
 mysqli_select_db($con, "bookstore") or die(mysqli_error()); 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Book Store</title>
</head>
<body>
<td><h1>Book Search</h1> </td>
<table width="100%" border="0">
  <tr>
    <form method="post" action="search.php?go" id="searchform">
      <input type="text" name="name">
      <input type="submit" name="submit" value="Search By Title">
    </form>
    <form method="post" action="search.php?go" id="searchform">
      <input type="text" name="category">
      <input type="submit" name="submit" value="Search By Category">
    </form>
  </tr>
</table>
</body>
</html>

以下是一个简单的search.php代码,用于查询我的数据库并返回结果。但是我无法看到任何结果。唯一显示的是“书名搜索结果”,下面没有任何内容。这显然意味着我的问题在于我的while循环。

<?php
 $con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
 mysqli_select_db($con, "bookstore") or die(mysqli_error()); 
?>

<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
<meta http-equic="Content-Type" content="text/html; charset=utf-8" />

</head>
<body>
<?php 
  if (isset($_POST['name'])){
    $query = $_POST['name'];
    $sql = mysqli_query($con, "SELECT * FROM books
    WHERE (`title` LIKE '%".$query."%')") or die(mysqli_error($con));

    if (mysqli_num_rows($sql) > 0) {
        echo "</br> Book Title Search Results </br>";
            while ($row = mysqli_fetch_array($sql, MYSQL_ASSOC)) {
                echo "</br>Title: " .$row['title']. ", Author: " .$row['author'].", Year: " .$row['year'] . ", Price: $" .$row['price'] ."</br>";
                echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['cover'] ).'"/>';
            }
    }else{ // if there is no matching rows do following
        echo "No results";
    } 
 }
?>
</body>
</html>

我的数据库中有6列:titleauthoryearpricecategoryimage(BLOB FILE) ,我已经检查了我的查询函数中的命名,但无法解决任何问题。任何人都可以把我推向正确的方向或告诉我我做错了什么?我正在使用MAMP网络服务器。

3 个答案:

答案 0 :(得分:3)

您的代码中存在拼写错误。使用MYSQLI_ASSOC代替MYSQL_ASSOC。其余代码是正确的。

答案 1 :(得分:1)

$con = mysqli_connect("localhost", "root", "root", "bookstore") or die("Error connecting to database: ".mysqli_error());

答案 2 :(得分:0)

在您的查询中,删除where:

后面的大括号
$sql = mysqli_query($con, "SELECT * FROM books WHERE title LIKE '%$query%'") or die(mysqli_error($con));

然后使用以下方法获取结果:

while ($row = mysqli_fetch_assoc($sql)) {
//code
}