检查while循环输出查询中的任何数据

$query=$db->prepare("SELECT *...
while($data=$query->fetch(PDO::FETCH_ASSOC)){...}

I have a query use while loop print out the data.

How can I check if while loop didn't fetch out any data(0 row from db), so I can print "0 result" on screen.

I don't want to make extra query for COUNT(*), is any way do check from while loop?

Just put a flag inside the loop to ensure you entered at least once.

Something like:

$flag = false;
$query=$db->prepare("SELECT *...");
while($data=$query->fetch(PDO::FETCH_ASSOC)){
    $flag = true;
}
if ($flag) {} //entered

Added semicolon, thanks @Fred -ii

You have to use $sth = $query->execute() (and $sth->fetch() instead of $query->fetch() ) first, then $sth->rowCount will give you the number of results.

So you want to count the amount of results you get. In that case, you can just count a var up inside the loop:

while($data=$query->fetch(PDO::FETCH_ASSOC)){
    $i++;
    //your code here
}

If you want to check if you got no data, you can check $data:

while($data=$query->fetch(PDO::FETCH_ASSOC)){
    if($data === false) {
       echo "0 result";
    }
}