Hi, Guest ~ Login or Register

Using COUNT()

Using COUNT()

Listed In PHP and MySQL » Database Interaction — Viewing Full Tutorial
If your database is getting slow these days with loads of content and lots of rows, and you're experiencing troubles with loadtime, it could be something to do with your counting up -- especially if you're dealing with a hell of a lot of rows.

Remember 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.

Working Beta

  1. The Forums
    These are mostly functional. If you see any weird bugs, post a thread about it and an administrator will do something.
  2. Tutorial Writing
    You can now submit tutorials to the brand new management system.
  3. Tutorials Home
    View tutorials by categories and search for them here.
  4. Shoutbox
    See below. Registered users only!

Register

Newest User

Say hi to Lirette25! Lirette25 joined on Monday, 14th July.

Sponsor

Check out Next day fake id

Shoutbox