Using COUNT()
Listed In PHP and MySQL » Database Interaction — Viewing Full TutorialRemember the old days when you used to do this?:
<?php $query = mysql_query("SELECT field1, field2 FROM table");
$numrows = mysql_num_rows($query);
?>Or even worse:<?php
$query = mysql_query("SELECT * FROM table");
$numrows = mysql_num_rows($query);
?>These query and then count, this isn't right. We need to use a special type of query that is used just for counting, YOU GUESSED IT - IT'S COUNT()!
This is how we do it:
<?php
$query = mysql_query("SELECT COUNT(*) AS num FROM table");
$query = mysql_fetch_array($query);
$number = $query['num'];
echo $number;
?>Baffled? Let me break it down for you.
Line one counts up the amount of rows in the table.
Line two fetches the array (the number)
Line three sets up the number.
Line four echos it.
Wondering where the array key, num came from? Let's go back to line 1 - notice COUNT(*) as num? Num basically identifies the array key that will be used when you count it all up.
That's all for now. Remember, even if your database is small, it's always a good idea to optimize queries before you get those problems.
