我如何使用json_encode()函数与MySQL查询结果?我是否需要遍历这些行,或者我可以将其应用到整个结果对象?


当前回答

试试这个,这将正确创建您的对象

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);

其他回答

根据我的经验,在命名根元素之前,上述方法是行不通的 数组中的东西,我还没有能够访问任何东西 最后的json。

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

这应该能奏效!

例如 $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.)如果$result只有一行。

$response = mysql_fetch_array($result);
echo json_encode($response);

2.)如果$result多于一行。你需要迭代这些行,并将其保存到一个数组中,并返回一个包含数组的json。

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);

我是这样解的

$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
    $list=array();
    $i=0;
    while ($cresult=$stmt->fetch()){    


        $list[$i][0]=$cde;
        $list[$i][1]=$v_off;
        $list[$i][2]=$em_nm;
        $list[$i][3]=$q_id;
        $list[$i][4]=$v_m;
        $i=$i+1;
    }
    echo json_encode($list);        

这将作为结果集返回给ajax 通过使用json解析javascript部分,像这样:

obj = JSON.parse(dataX);

试试这个,这将正确创建您的对象

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);

我们可以这样简化Paolo Bergantino的答案

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));