[英]PHP not returning mysql results
我是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列: title
, author
, year
, price
, category
, image
(BLOB FILE),並且我已經在查詢函數中檢查了命名,但找不到任何內容。 誰能將我推向正確的方向或向我展示我做錯了什么? 我正在使用MAMP Web服務器。
您的代碼中有一個錯字。 使用MYSQLI_ASSOC
代替MYSQL_ASSOC
。 其余代碼是正確的。
嘗試
$con = mysqli_connect("localhost", "root", "root", "bookstore") or die("Error connecting to database: ".mysqli_error());
在查詢中,在where后面刪除大括號:
$sql = mysqli_query($con, "SELECT * FROM books WHERE title LIKE '%$query%'") or die(mysqli_error($con));
然后使用以下命令獲取結果:
while ($row = mysqli_fetch_assoc($sql)) {
//code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.