JSON encode MySQL results

2018-12-31 03:02发布

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?

标签: php mysql json
20条回答
其实,你不懂
2楼-- · 2018-12-31 03:23

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);
查看更多
冷夜・残月
3楼-- · 2018-12-31 03:26

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);
查看更多
查无此人
4楼-- · 2018-12-31 03:28

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;
}   
查看更多
余生请多指教
5楼-- · 2018-12-31 03:29

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";
        }
查看更多
何处买醉
6楼-- · 2018-12-31 03:32

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);
?>
查看更多
人间绝色
7楼-- · 2018-12-31 03:36

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.

$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

查看更多
登录 后发表回答