简体   繁体   中英

PHP: Why mysqli_fetch_assoc() won't work? I am using mysqli_stmt_get_result()

I have a MySQL query that was working up until I changed it in order to use prepared statements. I cannot figure out why I do get this error:

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given

The query (of this log in form) should return just one result:

    $conectar = mysqli_connect(localhost, USER, PASS, DATABASE);

    //from the log in form
    $email = $_POST['email'];
    $clave = $_POST['clave']; 

//this should get me just one result: the user to which the email belongs.
    $consulta = "SELECT usuarios.userID, usuarios.userPass, usuarios.userEmail, usuarios.userPass, usuarios.userFechaGeneracion, usuarios.userNombres, rolesUsuarios.nombreRol,
                 GROUP_CONCAT(rolesUsuarios.nombreRol SEPARATOR '|') AS roles
                 FROM rolesUsuarios, usuarios 
                 WHERE usuarios.userEmail=?
                 AND rolesUsuarios.userID = usuarios.userID
                 GROUP BY usuarios.userID
                 ";
    $buscarUsuario = mysqli_prepare($conectar,$consulta);
    mysqli_stmt_bind_param($buscarUsuario, 's', $email);
    mysqli_stmt_execute($buscarUsuario);

        if (mysqli_stmt_get_result($buscarUsuario)) { 
            $row = mysqli_fetch_assoc($buscarUsuario);
            $originalPass = $row['userPass'];
...

Why isn't working? The query in itself should return an array with that result, containing the User Name Email, the Password (a hashed value, actually), his Role, etc...

You are close:

    //  vvvvvvv--- this is missing
    if ($result = mysqli_stmt_get_result($buscarUsuario)) { 
        $row = mysqli_fetch_assoc($result);
        //                        ^^^^^^^--- & needs to be used here

The reason is that $buscarUsuario is a statement "handle", not an actual result set from the database. You use that "handle" to get the actual result set. Following the trail of logic using the documentation:

mysqli_stmt_get_result takes a mysqli_stmt argument and returns a mysqli_result :

mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )

mysqli_fetch_assoc takes a mysqli_result :

array mysqli_fetch_assoc ( mysqli_result $result )

According to the documentation ( https://secure.php.net/manual/en/mysqli-stmt.get-result.php ), this is how you use mysqli's prepared statements, where $stmt is $buscarUsuario in your code snippet:

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries. Official Doc

while (mysqli_stmt_fetch($stmt)) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM