2016-07-26 19 views
-3

我想這是個小問題,但很樂意回答解釋。第8行產生未定義的變量錯誤(null)。接收「未定義的變量:第8行C: xampp htdocs xampp products products.php中的數據爲空」

<?PHP 
include_once("connectionFile.php"); 
$query = "SELECT pid, name, qty, price, image_url FROM tbl_product ORDER BY pid DESC"; 
$result = mysqli_query($con, $query); 
while($row = mysqli_fetch_assoc($result)){ 
$data[] = $row; 
} 
echo json_encode($data); 
?> 
+0

您提取了0行,所以您從未創建過'$ data'。 – Rizier123

+0

檢查'$ result'中是否有結果集或mysql執行錯誤,否則將'$ data'設置爲空字符串/對象。 – mitkosoft

回答

0

,因爲變量$data沒有定義之外。

<?PHP 
    include_once("connectionFile.php"); 
    $query = "SELECT pid, name, qty, price, image_url FROM tbl_product ORDER BY pid DESC"; 
    $result = mysqli_query($con, $query); 
    $data = array(); // add this or $data = []; 
    while($row = mysqli_fetch_assoc($result)){ 
    $data[] = $row; 
    } 
    echo json_encode($data); 

這不是一個致命錯誤,只是通知,您可以通過php.ini文件或使用error_reporting(E_ALL^E_NOTICE)功能設置的錯誤級別。

順便說一下,就像你寫的代碼是太舊了,我們強烈建議閱讀PHP The Right Wayhttp://www.phptherightway.com/

第一個答案,並希望它幫助。

+0

使用$ data = array(); 謝謝...! – user3537196

1

在while循環之外聲明您的$數據。如果你是內聲明,而$數據的環路範圍是在while循環,你續使用while循環

<?PHP 
include_once("connectionFile.php"); 
$query = "SELECT pid, name, qty, price, image_url FROM tbl_product ORDER BY pid DESC"; 
$result = mysqli_query($con, $query); 
$data=[]; 
while($row = mysqli_fetch_assoc($result)){ 
$data[] = $row; 
} 
echo json_encode($data); 
?> 

希望這將有助於

相關問題