kangkon.
kangkon.

Reputation: 21

mysqli_stmt::fetch(); returns a boolean value but is expected to return an array

I am making a simple Log-in feature, with code that has definitely worked (from a tutorial). It results in an error notice:

Notice: Trying to access array offset on value of type bool in

Why does $row = $query->fetch(); return a boolean value and not an array?

Result of the var_dump($query) with a correct login data:

object(mysqli_stmt)#2 (10) { 
    ["affected_rows"]=> int(-1) 
    ["insert_id"]=> int(0) 
    ["num_rows"]=> int(0) 
    ["param_count"]=> int(1) 
    ["field_count"]=> int(3) 
    ["errno"]=> int(0) 
    ["error"]=> string(0) "" 
    ["error_list"]=> array(0) { }
    ["sqlstate"]=> string(5) "00000" 
    ["id"]=> int(1) 
}

Result of the var_dump($row): bool(true)

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $email = trim($_POST["email"]);
    $password = trim($_POST["password"]);

        if($query = $db->prepare("SELECT * FROM user WHERE email = ? ")) {
            $query->bind_param("s",$email);
            $query->execute();
            var_dump($query);
            $row = $query->fetch();
            var_dump($row);
            if($row) {
                if(password_verify($password, $row['password'])) {
                    header("location:https://stackoverflow.com/");
                    exit;
                }
            }
         }
}

Upvotes: 1

Views: 1012

Answers (1)

Dharman
Dharman

Reputation: 33315

mysqli_stmt::fetch() method does not return an array. It always returns a boolean.

What you are looking for is the mysqli_result object. You can get that object by calling get_result(). This object has methods like fetch_assoc() that will return an array of values. For example:

$query = $db->prepare("SELECT * FROM user WHERE email = ? ");
$query->bind_param("s", $email);
$query->execute();
$row = $query->get_result()->fetch_assoc();
if ($row && password_verify($password, $row['password'])) {
    header("location:https://stackoverflow.com/");
    exit;
}

However, if you wish to select a single field from the database then you can use mysqli_stmt::fetch() but you must bind the SQL column to a PHP variable.

$query = $db->prepare("SELECT password FROM user WHERE email = ? ");
$query->bind_param("s", $email);
$query->execute();
$query->bind_result($hashedPassword);
if ($query->fetch() && password_verify($password, $hashedPassword)) {
    header("location:https://stackoverflow.com/");
    exit;
}

Upvotes: 2

Related Questions