-1

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

#1

$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?

yivi
  • 42,438
  • 18
  • 116
  • 138
  • 2
    `new mysqli` calls `__construct()` which calls `connect`, no difference. – AbraCadaver Nov 04 '20 at 22:18
  • 1
    Have a look at php.net/mysqli_connect - both are synonym – Nico Haase Nov 05 '20 at 12:27
  • Why would you expect a difference? What kind of difference are you interested in? You'll find many things that can be accomplished in many different ways across the language (and many other languages). – yivi Nov 06 '20 at 18:12

1 Answers1

1

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()

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Barmar
  • 741,623
  • 53
  • 500
  • 612