Error in a SQL query in PHP [duplicate]

3

I am having difficulties with a 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 \ trabalhowebGustavo \ user \ BancoEndereco.php on line 54

Here is 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 reporting the error - (54) , is the while line.
Any questions or additional information needed regarding the question, I am available.

    
asked by anonymous 24.05.2015 / 20:17

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

Looks like your query has a syntax error, two where in the same query what should be 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:

According to where, in this case $filtro has some value it will generate a query with the invalid syntax. I believe you should change where to AND in if below.

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

See a simplified example of how queries were generated.

    
24.05.2015 / 20:28