How do I properly use PHP to encode MySQL object into JSON?(如何正确使用 PHP 将 MySQL 对象编码为 JSON?)
问题描述
我正在尝试遍历 MySQL 对象并在另一个页面上使用 ajax 调用来附加数据,但我无法让 php 向回调返回有效的 JSON.
这个显然行不通...
query($myQuery) or die($mysqli->error);$row = $result->fetch_assoc();回声 json_encode($row);?>或者这个...
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 );这应该可以.此外,您可以使用 http://jsonlint.com/ 查看您的 JSON 输出有什么问题.>
更新:使用 fetch_all() 也可能是个好主意
$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 );
这篇关于如何正确使用 PHP 将 MySQL 对象编码为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确使用 PHP 将 MySQL 对象编码为 JSON?
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
