如何从mysqli结果中构建正确的json?

时间:2013-05-29 14:54:58

标签: php javascript json mysqli

我正在尝试从myqli结果中构建一个json对象。我该怎么做呢目前它不会创建一个json看对象。

这是我的代码:

$result = $dataConnection->prepare("SELECT id, artist, COUNT(artist) AS cnt FROM {$databasePrefix}users GROUP BY artist ORDER BY cnt DESC LIMIT 0 , 30");
$result->execute();
if($result->error)
{
die("That didn't work. I get this: " . $result->error);
}
$result->bind_result($id, $artist, $count);
$data = array();
while($result->fetch()){
$data[] = '{ id :'.$id.', artist :'.$artist.', count :'.$count.'}';
}
echo json_encode($data);
$dataConnection->close();

我想要一个数据对象,如:

{"id":"27","artist":"myArtist","count":"29"},....

4 个答案:

答案 0 :(得分:5)

$result = $dataConnection->query("SELECT id, artist, COUNT(artist) AS count FROM {$databasePrefix}users GROUP BY artist ORDER BY cnt DESC LIMIT 0 , 30");
$data = array();
while($row = $result->fetch_assoc()){
    $data[] = $row;
}
echo json_encode($data);

说实话,mysqli是在应用程序代码中使用的糟糕API。

帮自己一个忙,至少使用PDO

$result = $dataConnection->prepare("SELECT id, artist, COUNT(artist) AS count FROM {$databasePrefix}users GROUP BY artist ORDER BY cnt DESC LIMIT 0 , 30");
$result->execute();
echo json_encode($result->fetchAll());

与mysqli不同,它的方法始终有效。

答案 1 :(得分:2)

不要为你将在

上调用json_encode的values数组构建你的json

而不是:

$data[] = '{ id :'.$id.', artist :'.$artist.', count :'.$count.'}';

$data[] = array("id"=>$id, "artist"=>$artist, "count"=>$count);

答案 2 :(得分:2)

如果您使用mysqli这是一个例子。我将它与javascript ajax调用结合使用 输出如下所示: [{"field1":"23","field2":"abc"},{"field1":"24","field2":"xyz"}]

$mysqli = mysqli_connect('localhost','dbUser','dbPassword','dbName');

/* check connection */
if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
}

$query = "SELECT field FROM table LIMIT 10";

if ($result = mysqli_query($mysqli, $query)) {
  $out = array();

  while ($row = $result->fetch_assoc()) {
    $out[] = $row;
  }

  /* encode array as json and output it for the ajax script*/
  echo json_encode($out);

  /* free result set */
  mysqli_free_result($result);

  /* close connection*/
  $mysqli->close();
}

/* close connection*/
$mysqli->close();

答案 3 :(得分:-1)

只需创建所有行的数组,然后执行:

echo json_encode($array)