Error in SQL query in PHP

Asked

Viewed 1,780 times

3

I’m having difficulties with an SQL query in PHP, when I make a query I get the following error:

Warning: mysqli_fetch_assoc() expects Parameter 1 to be mysqli_result, Boolean Given in C: xampp htdocs trabowebGustavo usuario Bancoendereco.php on line 54

It follows the code below the function that returns the error:

function listaEnderecos($conexao, $filtro, $ordem, $usuario) {
$enderecos = array();
$sql = "select enderecos.*, us.email, cidades.nomecidade 
            from enderecos 
            inner join usuarios us on enderecos.idusuario = us.id
            inner join cidades on cidades.id =  enderecos.idcidade
            where us.email = {$usuario}";
if ($filtro <> "") {
    $sql = $sql .
       " where enderecos.idcidade like '%{$filtro}%'";
}
if ($ordem <> "") {
    $sql = $sql .
       " order by {$ordem}";
}
$resultado = mysqli_query($conexao, $sql );


while ($endereco = mysqli_fetch_assoc($resultado)) {
    array_push($enderecos, $endereco);
}
return $enderecos;
}

The line that reports the error - (54), is the line of while.
Any doubt or additional information required in relation to the question, I am available.

1 answer

2


mysqli_fetch_assoc() expects Parameter 1 to be mysqli_result, Boolean Given

This error means that your query failed because mysqli_query() returned a false(Boolean).

It looks like your query has a syntax error, two where in the same consultation what should be a or or and

$sql = "select enderecos.*, us.email, cidades.nomecidade 
            from enderecos 
            inner join usuarios us on enderecos.idusuario = us.id
            inner join cidades on cidades.id =  enderecos.idcidade
            where us.email = {$usuario}"; // primeiro where:

Second Where, here case $filtro has some value will generate a query with invalid syntax. I believe you should exchange the where by a AND if below.

if ($filtro <> "") {
    $sql = $sql .
       " where enderecos.idcidade like '%{$filtro}%'";
}

See a simplified example how queries were generated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.