What is the difference between mysqli::connect and new mysqli?

Tags: ,

Mysqli library offers a number of alternative syntaxes for establishing connection to the MySQL server.


$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

# 2

$mysqli = new mysqli();
$mysqli->connect('localhost', 'my_user', 'my_password', 'my_db');

I am not asking about procedural vs OOP style nor am I asking about mysqli_connect() vs mysqli_real_connect().

What is the purpose of the mysqli:connect() method, and is there any difference between connecting using the first option and the second option?


There’s no difference.

If you call new mysqli with arguments, it calls $this->connect() with those arguments automatically.

Otherwise it leaves the mysqli object unconnected, and you have to call the connect() method explicitly. That’s what method 2 is doing.

Using separate calls can be useful if you need to call mysqli::options() before connecting. Some of the options affect connecting to the DB, e.g. MYSQLI_OPT_CONNECT_TIMEOUT, so you need to set them before calling mysqli::connect()

Source: stackoverflow