php JSON 编码 MySQL 结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/383631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:33:44  来源:igfitidea点击:

JSON encode MySQL results

phpmysqljson

提问by Trick Jarrett

How do I use the json_encode()function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

如何将json_encode()函数与 MySQL 查询结果一起使用?我需要遍历行还是可以将其应用于整个结果对象?

回答by Paolo Bergantino

$sth = mysqli_query("SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

The function json_encodeneeds PHP >= 5.2 and the php-jsonpackage - as mentioned here

该函数json_encode需要 PHP >= 5.2 和php-json包 - 如这里所述

NOTE: mysqlis deprecated as of PHP 5.5.0, use mysqliextension instead http://php.net/manual/en/migration55.deprecated.php.

注意mysql自 PHP 5.5.0 起已弃用,请使用mysqli扩展名代替http://php.net/manual/en/migration55.deprecated.php

回答by ddavtian

Try this, this will create your object properly

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

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

 print json_encode($rows);

回答by Hugh Bothwell

http://www.php.net/mysql_querysays "mysql_query()returns a resource".

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

http://www.php.net/json_encodesays it can encode any value "except a resource".

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

You need to iterate through and collect the database results in an array, then json_encodethe array.

您需要遍历并将数据库结果收集到一个数组中,然后是json_encode该数组。

回答by Tokes

Thanks this helped me a lot. My code:

谢谢这对我帮助很大。我的代码:

$sqldata = mysql_query("SELECT * FROM `$table`");

$rows = array();
while($r = mysql_fetch_assoc($sqldata)) {
  $rows[] = $r;
}

echo json_encode($rows);

回答by aashima

Thanks.. my answer goes:

谢谢..我的回答是:

if ($result->num_rows > 0) {
            # code...
            $arr = [];
            $inc = 0;
            while ($row = $result->fetch_assoc()) {
                # code...
                $jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
                $arr[$inc] = $jsonArrayObject;
                $inc++;
            }
            $json_array = json_encode($arr);
            echo $json_array;
        }
        else{
            echo "0 results";
        }

回答by P?r

The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that.

以上是行不通的,根据我的经验,在将数组中的根元素命名为某些东西之前,在此之前我无法访问最终 json 中的任何内容。

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

That should do the trick!

这应该够了吧!

P?r

P?r

回答by ferreirabraga

The code below works fine here!

下面的代码在这里工作正常!

<?php

  $con=mysqli_connect("localhost",$username,$password,databaseName);

  // Check connection
  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $query = "the query here";

  $result = mysqli_query($con,$query);

  $rows = array();
  while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
  }
  echo json_encode($rows);

  mysqli_close($con);
?>

回答by James

My simple fix to stop it putting speech marks around numeric values...

我的简单修复是阻止它在数值周围放置语音标记......

while($r = mysql_fetch_assoc($rs)){
    while($elm=each($r))
    {
        if(is_numeric($r[$elm["key"]])){
                    $r[$elm["key"]]=intval($r[$elm["key"]]);
        }
    }
    $rows[] = $r;
}   

回答by gear4

Sorry, this is extremely long after the question, but:

对不起,这是在问题之后很长一段时间,但是:

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

Just basically:

基本上就是:

"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

回答by jrran90

we could simplify Paolo Bergantinoanswer like this

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

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