PHP - Mysqli correct way

Asked

Viewed 69 times

4

I’m starting to use mysqli in my projects, however I saw two ways to make a connection:

One of them is simple and equal to mysql_connect $db = mysqli_connect(...); I saw in w3schools.

Another is the $db = new mysqli('localhost', 'user', 'pass', 'demo');

Is there a difference between the two? Which is the best?

1 answer

8


There’s no better, in the end it’s all the same.

Looking at the PHP manual:

http://php.net/manual/en/function.mysqli-connect.php

You see that function mysqli_connect is synonymous with the method __construct() (which is what happens when you use the new), therefore,

$db = mysqli_connect('localhost', 'user', 'pass', 'demo');

is the very thing that

$db = new mysqli('localhost', 'user', 'pass', 'demo');


Use the one that "matches" the most with your code style. Since it is PHP, which is nothing more than a "script processor" that neither maintains the internal state between calls, unlike compiled languages where modules or even the entire application run in the same context, you can mix the paradigms without any problem, without significant advantages and disadvantages, and so ends up being a matter of "aesthetics" and really you choose what matches your workflow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.