問題描述
我在運行以下代碼以顯示從數據庫進行的預訂時遇到上述錯誤.
I'm getting the above error when running the below code to display bookings made from a database.
<?php
$servername = "localhost";
$username = "*********";
$password = "********";
$dbname = "thelibr1_fyp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, tablename, numseats, person FROM confirms";
$result = $conn->query($sql);
?>
<table id="Confirms" border ="2" style="length:900px;width:350px;">
<thead>
<tr style= "background-color: #A4A4A4;">
<td>Booking ID:</td>
<td>Table No.:</td>
<td>No. of Seats:</td>
<td>Person:</td>
</tr>
</thead>
<tbody>
<?php
while(($row = $result->fetch_assoc()) !== null){
echo
"<tr>
<td>{$row['id']}</td>
<td>{$row['tablename']}</td>
<td>{$row['numseats']}</td>
<td>{$row['person']}</td>
</tr>
";
}
?>
</tbody>
</table>
當我開始實時托管它時,我才開始收到錯誤消息.它在我的個人電腦上運行良好,數據庫連接也運行良好.
I only started to receive the error when i started hosting it live. It works fine on my personal computer, the databse connection works fine also.
推薦答案
query 方法可以返回 false
而不是結果集,以防出現錯誤.這就是為什么您會在 fetch_assoc 方法調用中出現錯誤的原因,當 $result 為 false
時,這顯然不存在.
The query method can return false
instead of a result set in case there is an error. That is why you get the error on the fetch_assoc method call, which obviously does not exist when $result is false
.
這意味著您的 SELECT 語句有錯誤.要顯示該錯誤,請執行以下操作:
This means you have an error in your SELECT statement. To get that error displayed, do this:
$result = $conn->query($sql) or die($conn->error);
很可能您對表名或列名的拼寫有誤.可能在移動到主機時您沒有正確創建該表,并在那里拼寫錯誤.
Most probably you have a wrong spelling for the table name or a column name. Maybe when moving to the host you did not create that table correctly, and made a spelling mistake there.
實際上,當您通過 phpAdmin 執行相同的查詢時,您應該會看到相同的錯誤.
You should in fact see the same error when executing the same query via phpAdmin.
另外,替換這一行:
while(($row = $result->fetch_assoc()) !== null){
只要:
while($row = $result->fetch_assoc()) {
你也可以添加這個用于調試:
You could also add this for debugging:
echo "number of rows: " . $result->num_rows;
這篇關于在 <path> 中的 boolean 上調用成員函數 fetch_assoc()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!