2016-04-25 330 views
-2

我試圖從數據庫中提取數據並將其轉換爲Json數據。無法從數據庫中提取數據並將其轉換爲Json數據

我有一個產品的ID,圖像,名稱和價格的表。我想將這些數據轉換成Json,然後將它們提取到我的網站。

<?php 
//config is the file where i used to connect php to db 

include_once('config.php'); 

// images is my table name 
$sql= "SELECT * FROM `images` "; 

$res= mysql_query($sql); 

$result = array(); 

while ($row = mysql_fetch_array($res)) 

//image is stored as longbob, name as varchar and price as int 

array_push($result, array('id'=> $row[0], 
          'image' = > $row[1], 
          'name'=> $row[2], 
          'price'=> $row[3] 
)) 




echo json_encode(array()); 




?> 
+0

是什麼問題?將$ result放入json_encode中,就像echo json_encode($ result); –

回答

0

你不需要array_push。只是繼續排列,像這樣做:

<?php 
//config is the file where i used to connect php to db 

include_once('config.php'); 

// images is my table name 
$sql= "SELECT * FROM `images` "; 

$res= mysql_query($sql); 
$result=array(); 
while (($row = mysql_fetch_array($res))!==false) 
{ 
    //image is stored as longbob, name as varchar and price as int 
    $result[] = array('id'=> $row[0], 
         'image' = > $row[1], 
         'name'=> $row[2], 
         'price'=> $row[3], 
         'error'=>false, 
         'error_message'=>'' 
       )); 

} 

if(count($result)>0) 
    echo json_encode($result); 
else 
    echo json_encode(array(array('error'=>true,'error_message'=>'No Images'))); 
?> 

我想你想在AJAX這個權利?如果您將在ajax中使用,只需在代碼的最後一行放置exit;即可。

我也爲你添加錯誤對象,你可以調試你的代碼或者只是檢查數據是否存在。

0

好,執行查詢

$result = array(); 
while ($row = mysql_fetch_array($res)) 
{ 
    //image is stored as longbob, name as varchar and price as int 
    $result[] = array('id'=> $row[0], 
         'image' = > $row[1], 
         'name'=> $row[2], 
         'price'=> $row[3] 
       )); 

} 
echo json_encode($result); 

你必須編碼$result,而不是array()後嘗試。

相關問題