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?
-
2No 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– FosAvanceCommented Mar 29, 2013 at 16:59
3 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
-
3The PHP manual isn't even very clear on the implications of using either... 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_dubbCommented Nov 26, 2019 at 22:12
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.
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.
-
Your answer is a little bit wrong. See stackoverflow.com/q/58808332/1839439– Dharman ♦Commented Jan 23, 2020 at 9:48