Tuesday 30 June 2015

PHP mysqli slow running/loading SQL statements

I've recently been working on a new system for a client - the last time that I did this I created my own object oriented implementation of the old MySQL function.

MySQL has since been superseded, and something similar to what I created is now part of PHP - called mysqli its one of two new interfaces that come as standard with PHP to run SQL scripts.

I've been making the system for a number of weeks now and performance has always been a little lackluster. Today, I decided to spend some time trying to optimize things and for the life of me I couldn't work out why running 5 SQL commands was taking over 8 seconds!

Loads of digging later, I've now managed to get the loading times to less than a second and I only needed to change one thing.

As an example, lets say my original connection string was:

$mysqli = mysqli_connect('localhost', $SQL_Username, $SQL_Password, $SQL_Database);

Well for some reason, my web-server didn't like using the DNS hostname of "localhost" and simply changing this to 127.0.0.1 (local loopback) solved all my speed issues.

$mysqli = mysqli_connect('127.0.0.1', $SQL_Username, $SQL_Password, $SQL_Database);

It certainly helped me - hopefully it'll help someone else out there

Cheers