I was chatting with a friend today about increasing the load time of pages and he mentioned to me that the "mysql_num_rows" is old and takes a lot of time.
Would replacing the mysql_num_rows with the code below be quicker?
$query = mysql_query("SELECT COUNT(*) FROM sent_messages WHERE from_sender = '".$_SESSION['id']."'") or die(mysql_error());
$result = mysql_fetch_array($query);
$count = $result['COUNT(*)'];
I don't know too much about time complexity and algorithms so any advice would be greatly appreciated.
Thanks
mysql_num_rows() is not old, but it's slower because it requires more data to be transfered between client and database. mysql_num_rows() is irreplaceable if you need to read data AND count it. I recommend this way if all you need is a count of records:
$query = mysql_query("SELECT COUNT(*) FROM sent_messages WHERE from_sender = '".$_SESSION['id']."'") or die(mysql_error());
$count = mysql_result($query,0);
Māris Kiseļovs' answer covers the ground here. However, I just want to add the following in order to avoid confusion:
In general, try and do as much work in the DB / query as possible. I.e., don't fetch a lot of data only to perform calculation and transformation in PHP (or any other language). Always seek to only request what you need from the DB, thus minimizing the data interchange.
In this specific case you'll be better off with the COUNT(*)
and mysql_result()
approach; performing the calculations in the DB layer, only requesting the needed data (the number of records).
However, were you to list the records, too (i.e., presenting the count and iterating over the set of records) you should just do a normal SELECT ... FROM ...
to fetch the records (in order to generate the list) and do mysql_num_rows()
on this result set (in order to get the count). In this case there would be no gain in a separate SELECT COUNT(*) ...
query since you are need the entire result set from the DB anyway.