本文介紹了如何正確使用 PHP 將 MySQL 對(duì)象編碼為 JSON?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在嘗試遍歷 MySQL 對(duì)象并在另一個(gè)頁(yè)面上使用 ajax 調(diào)用來(lái)附加數(shù)據(jù),但我無(wú)法讓 php 向回調(diào)返回有效的 JSON.
這個(gè)顯然行不通...
query($myQuery) or die($mysqli->error);$row = $result->fetch_assoc();回聲 json_encode($row);?>
或者這個(gè)...
query($myQuery) or die($mysqli->error);while ( $row = $result->fetch_assoc() ){回聲 json_encode($row) .", ";}?>
解決方案
$data = array();while ( $row = $result->fetch_assoc() ){$data[] = json_encode($row);}回聲 json_encode( $data );
這應(yīng)該可以.此外,您可以使用 http://jsonlint.com/ 查看您的 JSON 輸出有什么問(wèn)題.>
更新:使用 fetch_all()
也可能是個(gè)好主意
$data = $result->fetch_all( MYSQLI_ASSOC );回聲 json_encode( $data );
I am trying to iterate through a MySQL object and use an ajax call on another page to append the data but I can't get the php to return valid JSON to the callback.
This one obviously doesn't work...
<?php
$db_host = "localhost";
$db_user = "blah";
$db_pass = "blah";
$db_name = "chat";
$mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
$myQuery = "SELECT * FROM users";
$result = $mysqli->query($myQuery) or die($mysqli->error);
$row = $result->fetch_assoc();
echo json_encode($row);
?>
Or this one...
<?php
$db_host = "localhost";
$db_user = "blah";
$db_pass = "blah";
$db_name = "chat";
$mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
$myQuery = "SELECT * FROM users";
$result = $mysqli->query($myQuery) or die($mysqli->error);
while ( $row = $result->fetch_assoc() ){
echo json_encode($row) . ", ";
}
?>
解決方案
$data = array();
while ( $row = $result->fetch_assoc() ){
$data[] = json_encode($row);
}
echo json_encode( $data );
This should do it. Also, you can use http://jsonlint.com/ to see what are the problems with your JSON output.
Update: using fetch_all()
might be a good idea too
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
這篇關(guān)于如何正確使用 PHP 將 MySQL 對(duì)象編碼為 JSON?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!