gpt4 book ai didi

php - 使用 php 和 mysql 从表中获取所有用户

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

我试图从用户表中获取所有用户并以 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()

http://php.net/manual/fr/mysqli-stmt.num-rows.php

关于php - 使用 php 和 mysql 从表中获取所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39291837/

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