Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many rows in a mysql BEFORE fetch_assoc?

Tags:

php

mysqli

I am getting some data from the mysql through a select.

$result = mysqli_query($cxn, $query);

I then go through it with

if ($result!= false) {
    while ($row = mysqli_fetch_assoc($result)) {
        do_stuff();
    }
}

What I'd like to do is to add a line before the while ONLY if there is more than one line in the $result.

I understand that I could create an array of $row's first and then count them, but that would defeat the convenience of the while.

Question: is there a way to find out how many rows the mysqli_fetch_assoc would generate without running it twice?

like image 328
Uno Mein Ame Avatar asked Jan 14 '23 18:01

Uno Mein Ame


2 Answers

You should check this function: http://php.net/mysqli_num_rows

You can check the number of results by using it like this

if (mysqli_num_rows($result))
{
..
}
like image 98
mishu Avatar answered Jan 18 '23 23:01

mishu


use http://php.net/mysqli_num_rows which returns count of rows in result

if(mysqli_num_rows($result) > 1)
like image 44
mychalvlcek Avatar answered Jan 18 '23 22:01

mychalvlcek