1

我正在尝试从我的 mysqli 结果构建一个 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

4 回答 4

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 不同,它的方法总是有效的。

于 2013-05-29T14:58:21.133 回答
2

不要为将调用 json_encode 的 values 数组构建 json

代替:

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

$data[] = array("id"=>$id, "artist"=>$artist, "count"=>$count);
于 2013-05-29T14:57:56.830 回答
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();
于 2014-07-08T15:15:47.327 回答
-1

只需创建一个包含所有行的数组,然后执行:

echo json_encode($array)
于 2013-05-29T14:58:54.940 回答