October 2004
Mon Tue Wed Thu Fri Sat Sun
<<  <   >  >>
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Categories

powered by

Valid XHTML 1.0!

09/26/04

11:44:32 am, Categories: DB Hoopla, 160 words  

When Newbies Attack!

I think inexperienced web programmers all make common DB WTFs when starting out. Jim Grill sent in a prime example from a project that he inherited. I'm sure we've all seen similar code before and we've all said, "wtf?!", if not "ytf?!"

<?php
$query = 'SELECT * FROM sometable';
$result = mysql_query($query,$connection);
$count = mysql_num_rows($result);
?>

It should be obvious what's wrong in the example. To count the number of rows all data is needlessly requested and the rows counted in PHP. As the table grows these three lines will get slower and slower. Most people take data transfer from the DB server for granted. However we always should be as efficient as possible, since little things can quickly multiply into big problems.

The fix is relatively simple:

<?php
$query = 'SELECT COUNT(*) FROM sometable';
$result = mysql_query($query,$connection);
list($count) = mysql_fetch_array($result);
?>

Using count(*) will return just the number of rows. Much more efficient.

Trackback address for this post:

http://thephpwtf.com/htsrv/trackback.php?tb_id=28

Comments, Trackbacks, Pingbacks:

No Comments/Trackbacks/Pingbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.
Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, a, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
URLs, email, AIM and ICQs will be converted automatically.
Options:
 
(Line breaks become <br />)
(Set cookies for name, email & url)