gpt4 book ai didi

php - 如何通过 php 从 mysql 数据库返回多行/所有行并制作 json?

转载 作者:行者123 更新时间:2023-11-29 12:12:12 27 4
gpt4 key购买 nike

我的 php 文件中有这个:

$response = array();
$user = $db->test($email);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["user"]["email"] = $user["email"];
$response["user"]["imagepath"] = $user["imagepath"];
$response["user"]["about"] = $user["about"];

echo json_encode($response);
} else {
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "JSON Error occured in db";
echo json_encode($response);
}

测试函数是

public function test($email){
$result = mysql_query("SELECT * FROM activities WHERE email = '$email'");
// return user details
return mysql_fetch_array($result);
}

测试函数返回多行,但 php 仅发送数据库中与该电子邮件匹配的第一行的 json。如何制作 foreach() 或类似的东西来对测试函数返回的所有内容进行编码?

最佳答案

首先你必须拒绝使用 mysql_fetch_array() 函数(读 this )。

接下来,您必须了解变量“user”包含所有找到的用户的列表(公平地说,它应该称为“users”)

$response = array();
$users = $db->test($email);
foreach($users as $user){
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["users"][] = array(
"email" => $user["email"],
"imagepath" => $user["imagepath"],
"about" => $user["about"]
);
} else {
if( empty($response) ){
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "JSON Error occured in db";
}
}
}
echo json_encode($response);

并更新测试功能:

public function test($email){
$result = mysql_query("SELECT * FROM activities WHERE email = '$email'");
// get all users details
$users = array();
while($user = mysql_fetch_array($result)){
$users[] = $user;
}
return $users;
}

关于php - 如何通过 php 从 mysql 数据库返回多行/所有行并制作 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30445874/

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