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

问题描述 投票:0回答:2

我正在编写 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 致命错误:在 file.php 中的非对象上调用成员函数 fetch_assoc()

file.php 中 mysqli_stmt::bind_result() 的参数计数错误。

php mysqli
2个回答
2
投票

选项 1 如果您安装了 MySQL 本机驱动程序 (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

-1
投票
$user = $stmt->bind_result()->fetch_assoc();

bind_result()
返回
bool
。您正在尝试使用此语法调用
bool::fetch_assoc()

© www.soinside.com 2019 - 2024. All rights reserved.