简体   繁体   中英

MySQL - PHP - Avoiding multiple queries to count results

I am trying to get some results for a query and count all the data results using PHP.

Actually I'm doing something like this:

$MQ=$cnx->query("SELECT COUNT(id) FROM table WHERE field=1;");
$MFA=$cnx->fetch_row();
$count=$MFA[0];
echo "Showing $count results";
$MQ=$cnx->query("SELECT id,name FROM table WHERE field=1;");
while($MFA=$MQ->fetch_assoc()){
  // show something with $MFA[id] and $MFA[name]
}

I want to avoid using 2 queries, Is there any way to get the rows count and then get all the results without using an array?

You can use the num_rows property to get the number of rows in a result set.

$MQ=$cnx->query("SELECT id,name FROM table WHERE field=1;");
$count=$MQ->num_rows;
echo "Showing $count results";
while($MFA=$MQ->fetch_assoc()){
  // show something with $MFA[id] and $MFA[name]
}

Is there any way to get the rows count and then get all the results without using an array?

There is, but you don't need it.

In fact, you should use an array , to separate your business logic from presentation logic.

And as long as you have an array, you can always count it's members.

You definitely should quit the practice of showing the query results right during the query execution. Instead, learn logic separation and use of templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM