MYSQL Error : Warning: mysqli_fetch_assoc() expect

2019-03-07 05:34发布

Is there anything wrong with my sql query ? I always get this error "Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given". Hope you can help me.

<?php
include("connection.php");
$mysqli->query("SET NAMES 'utf8'");
$filter = "All";

if ($filter == "All"){
    $sql="SELECT * FROM city ";
}else if($filter == "Alphabetically"){
    $sql="SELECT * FROM city order by cityName ASC";
}else if ($filter == "Region"){
    $sql="SELECT * FROM city order by region";
}else{
    echo "Error sql";
}
$result=$mysqli->query($sql);
while($e=mysqli_fetch_assoc($result)){
    $output[]=$e; 
}

print(json_encode($output)); 
$mysqli->close();
     ?>

标签: php mysql mysqli
2条回答
我只想做你的唯一
2楼-- · 2019-03-07 05:36

If your query have any sql error or its returning 0 rows. So check first num_row count

$result=$mysqli->query($sql);
if(mysqli_num_rows($result) > 0 ){       
    while($e=mysqli_fetch_assoc($result)){
                    $output[]=$e; 
                }
        }
        print(json_encode($output)); 
        $mysqli->close();

For any mysql error.

 $mysqli->error;
查看更多
老娘就宠你
3楼-- · 2019-03-07 05:48

I assume you are connecting to the database using the OO mechanism in mysqli as that is what you are using for almost all your mysqli commands

But here

while($e=mysqli_fetch_assoc($result)){

you have changed to the proceedural function calls.

Instead use

while($e = $result->fetch_assoc()){
查看更多
登录 后发表回答