J'essaie de construire un objet json à partir de mon résultat mysqli. Comment puis-je m'en occuper. En ce moment, il ne crée pas d'objet json.
Voici mon code:
$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();
Je souhaite un objet de données comme:
{"id":"27","artist":"myArtist","count":"29"},....
Ne créez pas votre json pour le tableau de valeurs auquel vous allez appeler json_encode
au lieu de:
$data[] = '{ id :'.$id.', artist :'.$artist.', count :'.$count.'}';
faire
$data[] = array("id"=>$id, "artist"=>$artist, "count"=>$count);
$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);
Pour vous dire la vérité, mysqli est une API horrible à utiliser directement dans le code de l'application.
Faites-vous une faveur et utilisez au moins une AOP
$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());
À la différence de mysqli, ses méthodes fonctionnent toujours.
Si vous utilisez mysqli, voici un exemple. Je l'utilise en combinaison avec un appel javascript ajax.
La sortie ressemble à ceci: [{"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();
Créez simplement un tableau de toutes vos lignes, puis faites:
echo json_encode($array)