Rosamunda Rosamunda - 1 year ago 64
MySQL Question

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

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

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...

Answer Source

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 )