42

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?

1
  • 2
    No it isn't, I tried to google it, but I thought that experience of people here could help me better and give me straight information about it
    – FosAvance
    Commented Mar 29, 2013 at 16:59

3 Answers 3

61

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

2
  • 3
    The PHP manual isn't even very clear on the implications of using either...
    – Alkanshel
    Commented Sep 5, 2018 at 18:44
  • what's the best practice? recreate the connection after each query? or allow the connection to persist?
    – b_dubb
    Commented Nov 26, 2019 at 22:12
14

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.

0

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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