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


当前回答

例如 $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);

其他回答

http://www.php.net/mysql_query说“mysql_query()返回一个资源”。

http://www.php.net/json_encode说它可以编码任何值,“除了资源”。

您需要在数组中遍历和收集数据库结果,然后对数组进行json_encode。

抱歉,这是在问题之后很长一段时间,但是:

$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]") 
AS json 
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);

基本上:

"SELECT" Select the rows    
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

函数json_encode需要PHP >= 5.2和PHP -json包-正如这里提到的

注意:mysql在PHP 5.5.0已弃用,请使用mysqli扩展http://php.net/manual/en/migration55.deprecated.php。

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

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

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

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

 print json_encode($rows);