gpt4 book ai didi

php - 编码 PHP MySQL 对 JSON 问题的查询响应

转载 作者:行者123 更新时间:2023-11-30 22:24:19 24 4
gpt4 key购买 nike

我基本上是在尝试调用 MySQL 查询并从服务器获取响应,我已经完成了并且它有效。现在我需要将响应编码为 JSON 数组(每行作为 JSON 对象并将它们添加到 JSON 数组)

我的代码:

foreach ($db->query('SELECT * from mydb.UserTable') as $sqlresp) {
$rows = array();
while($r = mysqli_fetch_assoc($sqlresp)) {
$rows['users'][] = $r;
}
print json_encode($rows);
}

上面的代码给我这个错误:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, array

它指向这一行:

while($r = mysqli_fetch_assoc($sqlresp)) {

JSON 数组中我需要的 JSON 对象:

大致就是这样的结构..

user
{
name: "john",
picture: "http://...."
details {
email: "email@gmail.com",
telephone: "3456..."
}
}

*表格的列名与对象属性名相同(例如:名称、图片等)

伙计们,我的代码有什么问题以及如何将查询响应的行正确编码为 JSON 数组?

编辑:

我需要数组,因为我需要将此数组发送到 Javascript 函数。所以我需要它的 JSON 数组格式

最佳答案

什么是$db,如果是mysqli连接资源,那么就支持

海事组织,

$sqlresp=$db->query('SELECT * from mydb.UserTable');

它是自定义库,它返回数组

所以你可以使用

echo json_encode( $sqlresp );

关于php - 编码 PHP MySQL 对 JSON 问题的查询响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com