2016-09-27 56 views
-1

任何人都可以幫助我做到這一點。我試圖從表中獲取所有數據。但它仍然以布爾值的形式返回。爲什麼說布爾被賦予

<?php 
    $con = mysqli_connect("localhost", "root", "", "student"); 

    $query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC"; 

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

    while($row = mysqli_fetch_assoc($result)){ 
     $data[] = $row; 
    } 

    echo json_encode($data); 
?> 

給出的錯誤是:

> Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, 
> boolean given in D:\Xampp\htdocs\student\announcement.php on line 8 
> 
> Notice: Undefined variable: data in 
> D:\Xampp\htdocs\student\announcement.php on line 12 null 
+0

總是檢查錯誤'($ con,$ query)或死($ con>錯誤)' – Ghost

+2

您的查詢失敗,它返回布爾值false – nogad

+0

[mysqli \ _fetch \ _array()/ mysqli \ _fetch \ _assoc()/ mysqli \ _fetch \ _row()期望參數1是資源或mysqli \ _result,布爾給定](http://stackoverflow.com/questions/2973202/mysqli-fetch-array-mysqli-fetch-assoc -mysqli-fetch-row-expects-parameter-1) –

回答

0

因爲mysqli_query返回false,$ result包含bool(false),並且mysqli_fetch_assoc需要一個mysqli_result對象,並且它在您給它一個bool代替時抱怨。我們不知道爲什麼mysqli_query返回false,並且因爲您沒有啓用錯誤報告,PHP不會告訴您爲什麼。你需要在你的代碼中檢查錯誤,以便早日發現,並讓php告訴你什麼是錯的。最簡單的方式做到這一點:與

<?php 
error_reporting(E_ALL); 
if(!mysqli_report(MYSQLI_REPORT_ALL)){ 
throw new RuntimeException("unable to set mysqli_report to MYSQLI_REPORT_ALL !"); 
} 

我也建議運行錯誤處理程序錯誤轉化爲例外,這樣

function exception_error_handler($severity, $message, $file, $line) { 
    if (!(error_reporting() & $severity)) { 
     // This error code is not included in error_reporting 
     return; 
    } 
    throw new ErrorException($message, 0, $severity, $file, $line); 
} 
set_error_handler("exception_error_handler"); 

現在PHP應該給出一個詳細的報告時錯誤啓動腳本發生了,包括爲什麼你的mysqli_query返回false。

0

請確保您在 「通知」 表數據。

您可以使用mysqli_num_rows()函數檢查結果集中返回的行數。

試試這個:

$con = mysqli_connect("localhost", "root", "", "student"); 
$query = "SELECT * FROM `announcement` ORDER BY `announce_id` DESC"; 
$result = mysqli_query($con, $query); 

$rowcount = mysqli_num_rows($result); //returns number of rows 

if($rowcount > 0) { 
    while($row = mysqli_fetch_assoc($result)){ 
    $data[] = $row; 
    } 
    echo json_encode($data); 
} 

讓我們知道對於櫃面相同的任何查詢/關注。

+0

他的問題是查詢錯誤或連接錯誤而不是空表 –

相關問題