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

时间:2016-04-25 01:42:45

标签: php 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());




?>

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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;放在代码的最后一行。

我还添加了错误对象,您可以调试代码或只检查数据是否存在。