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?

pandorym
  • 475
  • 4
  • 14
FosAvance
  • 2,363
  • 9
  • 36
  • 52
  • 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 Mar 29 '13 at 16:59

3 Answers3

59

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

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
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.

Rick Buczynski
  • 827
  • 8
  • 23
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.

Sabith
  • 1,628
  • 2
  • 20
  • 38
Danial
  • 21