Use your tools wisely

If you're shockingly lazy, you might be tempted to write pages with sections of code like this:

$result = mysqli_query($db, "SELECT * FROM Users;");
while ($row = mysqli_fetch_assoc($result)) {
    if ($row['ID'] < '30') {
        // do stuff here
    }
}

As you can see, they are using PHP to filter their SQL results - looking through the entire result set for particular rows.

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 = mysqli_query($db, "SELECT * FROM Users WHERE ID < 30;");
while ($row = mysqli_fetch_assoc($result)) {
    // do stuff here }

For very complicated SQL manipulation, consider using 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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Use some functions carefully for maximum performance >>

Previous chapter: Write your code sensibly

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.