36

I'm using PDO in my PHP application. It connects to a MySQL server on the same server:

$db = new PDO(mysql:host=localhost;dbname=test, $username, $password);

I created two pages with the same output (just some dummy data in plain html) one of which contains the call to create PDO. If I open the page that uses no connection the response is between 0.5 and 1 second quicker.

4
  • How do you get data from a database without a connection?
    – deceze
    Mar 21, 2012 at 7:59
  • The dummy data is just some plain HTML, nothing from the database. Mar 21, 2012 at 8:02
  • 1
    That effect is not normal. Seems like you have server-related issues. Maybe SQL server is slow to respond. Try to investigate more, but to me this seems more like ServerFault problem.
    – tereško
    Mar 21, 2012 at 8:03
  • See also $host=gethostbyname('localhost') at stackoverflow.com/a/16233679/1854563 Apr 28, 2014 at 8:12

1 Answer 1

82

I've been doing some googling, and after reading this thread, I changed localhost to 127.0.0.1. That solves the problem....

6
  • 2
    You made my day! Using localhost it took a whole second to connect, using 127.0.0.1 it takes about one millisecond.
    – CodeZombie
    Feb 8, 2013 at 0:41
  • 1
    Very helpful research. I tried to find the solution for while until this helped. Dropped from 1s to less than 3ms. Jul 29, 2013 at 19:30
  • 10
    A little 'why': By using a hostname, PHP is forced to do a lookup in the DNS table (slow!). If this is a big table, it can take a long time before the entry is found. By using a static IP address you can skip this resolving altogether. You can even do this in production with non-localhost IP's!
    – Gerben
    Aug 1, 2013 at 14:33
  • DNS is slow, but not THAT slow. There must be something else at play here. Same happened for me 1sec down to ms. Thanks for posting, very helpful Aug 8, 2014 at 12:47
  • @AshMcConnell Would you happen to be using Windows 8? I believe it's an issue in Windows 8.
    – mpen
    Sep 16, 2014 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.