我试图从用户表中获取所有用户并以 JSON 形式返回响应,但即使表上有数据,我也始终收到表为空的错误。
我的代码:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// fetching all users
$result = $db->getAllUsers();
if($result != NULL){
$response["error"] = false;
$response["users"] = array();
// looping through result and preparing users array
while ($user = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $user["id"];
$tmp["first_name"] = $user["first_name"];
$tmp["last_name"] = $user["last_name"];
$tmp["mobile"] = $user["mobile"];
$tmp["fcm_token"] = $user["token"];
array_push($response["users"], $tmp);
}
} else {
$response["error"] = true;
$response["message"] = "No users found on DB";
}
echo json_encode($response);
?>
getAllUsers
函数:
public function getAllUsers(){
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
if($stmt->num_rows > 0){
$users = $stmt->get_result();
$stmt->close();
return $users;
} else {
return NULL;
}
} else {
return NULL;
}
}
最佳答案
试试这个
$stmt = $this->conn->prepare("SELECT u.id, u.first_name, u.last_name, u.mobile, u.token FROM users u");
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows > 0){
$users = $stmt->get_result();
$stmt->close();
return $users;
} else {
return NULL;
}
} else {
return NULL;
}
在 getAllUsers 函数中(在 if(stmy_num-rows) 之前添加 $stmt->store_result()
关于php - 使用 php 和 mysql 从表中获取所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39291837/