无法从数据库中提取数据并将其转换为Json数据

问题描述:

我试图从数据库中提取数据并将其转换为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); –

你不需要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;即可。

我也为你添加错误对象,你可以调试你的代码或者只是检查数据是否存在。

好,执行查询

$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()后尝试。