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

标签 php mysql

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

相关文章:

MySQL 中的 Javascript 数组

java - 从 ajax 客户端调用时,如何通过身份验证确保 Web 服务的安全?

PHP/AJAX 插入 mysql 数据库时出现问题

C# MySQL 错误 System.Data.SqlClient.SqlException :

mysql - 通过 Codeigniter DBforge 类创建 MySQL 表

php - InnoDB 未提交但已写入(使用带有动态函数名的 PHP)

PHP/mySQL 数据未显示在表中

php - httpd.conf 虚拟主机不工作

php - 无法在 PHP 中使用 PDO 获取错误信息

PHPExcel 将 48 行中的 38 行从 xlsx 文件插入 MySQL