18.1.2 Use your tools wiselyThis is NOT the latest copy of this book; click here for the latest version.
At various times through my PHP career, I have seen pages with sections of code like this:
$result = mysql_query("SELECT * FROM Users;");
while ($row = mysql_fetch_assoc($result)) {
if ($row['ID'] == '3') {
// do stuff here
}
}
As you can see, they are using PHP to filter their SQL results - looking through the entire result set for a particular row.
SQL is designed to extract specific data from a database, and you should exploit its power as much as possible. MySQL is blazingly fast at processing queries, and modifying the above code to the following would yield an exponential speed increase:
$result = mysql_query("SELECT * FROM Users WHERE ID = 3;");
while ($row = mysql_fetch_assoc($result)) {
// do stuff here }
For very complicated SQL manipulation, you should use temporary tables - more information can be found on temporary tables in the Databases chapter.
A similar problem exists when people use functions that are more complex than is required for the task. For example, preg_replace() is a powerful way to search and replace text in a string, but if you are not doing regular expressions you should be using str_replace() as it's much faster. Similarly, explode() is a better choice than preg_split() when regular expressions are not required.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|