Home » Php » php – new mysqli vs mysqli_connect

php – new mysqli vs mysqli_connect

Posted by: admin April 23, 2020 Leave a comment

Questions:

What is difference between the new mysqli and mysqli_connect?
I know that executing a query is different;

for example: mysqli->query() and mysqli_query()

Why are there two different types, what is the need for the difference?

How to&Answers:

One is for Procedural style programming and other is for OOP style programming. Both serve the same purpose; Open a new connection to the MySQL server

OOP Style usage

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

Procedural Style usage

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

Reference: PHP Manual

Answer:

Right on @Hanky Panky. I’d also add to that the PHP docs:

http://www.php.net/manual/en/mysqli.construct.php

Note:

OO syntax only: If a connection fails an object is still returned. To
check if the connection failed then use either the
mysqli_connect_error() function or the mysqli->connect_error property
as in the preceding examples.

So error handling is just one difference.

Answer:

I just found a subtle but interesting difference between the two.

If you encounter a connection error with mysqli_connect (like $connection = mysqli_connect()), no mysql info will be returned to the $connection variable. As such, you will not be able to identify the error with myqli_errno($connection).

However if you encounter a connection error using new mysqli (like $connection = new mysqli()), the mysql info WILL be returned and you can check the error with $connection->connect_errno.

Knowing this, I’d opt for new mysqli.

Oops… Just saw answer from Rick Buczynski and realized after posting that I’m restating what he said, but his reply is more informative.