Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my MySQLi connection so slow?

Tags:

php

mysql

It takes for my local system about 1 second to establish a MySQLi connection. Code:

$db = new mysqli( 'localhost', 'root', 'pass', 'mydb' );

Why is it so slow? Is this normal? Can I improve it?

like image 247
Crayl Avatar asked Nov 18 '12 11:11

Crayl


2 Answers

Switch "localhost" to 127.0.0.1.

So, instead of:

$db = new mysqli( 'localhost', 'root', 'pass', 'mydb');

Use:

$db = new mysqli( '127.0.0.1', 'root', 'pass', 'mydb');

Seeing as this question seems to be pretty popular and a lot of people would like to know WHY this is happening:

This is caused because the MySQL client will do an IPV6 lookup for the hostname. If this fails (and in this case, it obviously does), it will then attempt to do an IPV4 lookup. Between the IPV6 (AAAA) lookup failing and the IPV4 (A) lookup succeeding, what we get is a connection timeout cycle that lasts about 1-2 seconds.

Worth noting that this problem only seems to occur with Windows 7 and after. Before Windows 7, localhost resolution was handled by the hosts file, which came pre-configured with 127.0.0.1

like image 112
Wayne Whitty Avatar answered Oct 22 '22 15:10

Wayne Whitty


As suggested by Tony:

I edited the Mysql my.ini to change the mysql service to only bind to the IPV4 loopback adapter.

[mysqld]
...
bind=127.0.0.1
like image 26
NullPoiиteя Avatar answered Oct 22 '22 14:10

NullPoiиteя