Warning: mysqli_fetch_assoc () expects parameter 1 to be mysqli_result, boolean given

1

I have a problem with the following code to print the contents of a database:

$k = $_POST['key'];
$consulta = 'SELECT * FROM ltr WHERE letter_key= $k';
$ejecutar= $conexion->query($consulta);
while ($row = mysqli_fetch_assoc($ejecutar)) {
    echo $row['letter'];
    echo $row['date'];
}

The problem is that that code throws me the error:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

And I do not know what could be due, because if I modify the query to:

'SELECT * FROM ltr'

I do not get any errors and the result is printed on the screen. Could it be that I'm doing the query incorrectly?

    
asked by kalia 01.08.2017 в 13:47
source

1 answer

7

The error occurs because mysqli :: query returns FALSE in case of an error query. link

Your query is failing because you can not add $ k to the string implicitly if you use single quotes. You must use double quotes.

Right now you are asking your database to return a letter whose key is $ k (literally, not the value of $ k).

Anyway, add a condition to the code just in case:

$k = $_POST['key'];
$consulta = "SELECT * FROM ltr WHERE letter_key = $k";
$ejecutar= $conexion->query($consulta);

if($ejecutar) {
    while ($row = mysqli_fetch_assoc($ejecutar)) {
        echo $row['letter'];
        echo $row['date'];
    }
}

Remember also that if letter_key is not an INT, you will have to surround '$ k' with single quotes.

    
answered by 01.08.2017 / 13:50
source