mina
mina

Reputation: 73

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

I am coding PHP and here is my code:

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;
    }
}

but I am getting this error and this warning and do not know how to solve it:

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.

Upvotes: 1

Views: 135

Answers (2)

Armen
Armen

Reputation: 4192

OPTION 1 if you have MySQL Native Driver (mysqlnd) installed you can use

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

more info here with examples: http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli

OPTION 2 if no then use it with bind_result, more info here for 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

Upvotes: 2

Darwin von Corax
Darwin von Corax

Reputation: 5246

$user = $stmt->bind_result()->fetch_assoc();

bind_result() returns bool. You're trying to call bool::fetch_assoc() with this syntax.

Upvotes: -1

Related Questions