PHP:调用 file.php 中非对象的成员函数 fetch_assoc()

标签 php mysql server

我正在编写 PHP,这是我的代码:

public function storeUser($name, $email, $password) {
    $uuid = uniqid('', true);
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt

    $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
    $result = $stmt->execute();
    $stmt->close();

    // check for successful store
    if ($result) {
        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $user = $stmt->bind_result()->fetch_assoc();
        $stmt->close();

        return $user;
    } else {
        return false;
    }
}

但我收到此错误和此警告,但不知道如何解决:

PHP Fatal error: Call to a member function fetch_assoc() on a non-object in file.php

Wrong parameter count for mysqli_stmt::bind_result() in file.php.

最佳答案

选项 1 如果您安装了 MySQL native 驱动程序 (mysqlnd),则可以使用

$res = $stmt->get_result();
$user = $res->fetch_array(MYSQLI_ASSOC);

这里有更多信息和示例:http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli

选项 2 如果否,则将其与 bind_result 一起使用,有关 bind_result 的更多信息,请参见此处:http://php.net/manual/en/mysqli-stmt.bind-result.php

// IMPOTANT: you need to change your sql query to select 
// only columns which you need unique_id, name, email ...
$stmt = $this->conn->prepare("SELECT unique_id, name, email FROM users WHERE email = ?");

$stmt->bind_param("s", $email);
$stmt->execute();

// list here variables with exact amount of columns which you selecting in your query 
$stmt->bind_result($row_user_id, $row_user_name, $row_user_email);

// In case you expect 1 row 
$stmt->fetch();
var_dump($row_user_id, $row_user_name, $row_user_email);// to see result
$user = array(
     'id' => $row_user_id, 
     'name' => $row_user_name,
     'email' => $row_user_email,
);

// In case you expect many rows use while 
$users = array();
while ($stmt->fetch())
{
   $users[] = array(
        'id' => $row_user_id, 
        'name' => $row_user_name,
        'email' => $row_user_email,
   );
}
var_dump( $users );// to see result

关于PHP:调用 file.php 中非对象的成员函数 fetch_assoc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378468/

相关文章:

javascript - 如何在php中自动输入MySQL数据(输入第1列数据到自动输入同一列的第2列数据)?

php - 使用数组的 str_replace 是格式化一个人的姓氏的正确方法吗?

mysql - 数据库在 QuerySet.datetimes() 中返回无效值

powershell - 如果使用率高于%PowerShell,则向用户发送电子邮件

php - 如何使用 json 选择

php - 从 mysql 行执行 php 脚本

php - 需要获取任务标签在 $TagArray 中的任务

mysql - 是否可以及时将 MySQL 数据库恢复到以前的状态?

algorithm - 服务器如何避免MMO游戏流量呈二次方增长?

javascript - 我如何从服务器端java代码调用Javascript函数并向其传递数据?