Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check, if there are still rows left from fetch_assoc loop?

Tags:

php

mysql

mysqli

I loop trough the rows with this code:

while ($row = $result->fetch_assoc()) {
    //...
}

But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()

like image 239
Iter Ator Avatar asked Dec 06 '22 21:12

Iter Ator


2 Answers

Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.

$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
    if(++$loop_ct < $row_cnt) {
        //do something
    }
} 
like image 92
VerySeriousSoftwareEndeavours Avatar answered Jan 05 '23 06:01

VerySeriousSoftwareEndeavours


I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:

$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
    //....
    $cnt--;
    if($cnt == x){ //Where x is the number you want
        //....
    }
}
like image 45
icecub Avatar answered Jan 05 '23 07:01

icecub