We see in many places these two types of code for creating database connection in PHP with Mysqli, so what is the technical difference between them?
$conn = mysqli_connect($host,$username,$password,$db_name);
And
$conn = mysqli_connect($host,$username,$password);
$db_selected = mysqli_select_db($conn,$db_name);
There is none. They are the same. There is also a third, better way which you have not listed here.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli($host, $username, $password, $db_name);
$conn->set_charset('utf8mb4');
OOP style is easier to read and less prone to errors. Additionally you should always enable exception mode and specify the correct connection charset. This is the best way.
From the PHP manual for mysqli_select_db
:
Note:
This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().
Setting a database name upon connection is just a convenient short-cut since most of the times you want to start using some specific database immediately.
Perhaps you're confused because you assume that a database connection is restricted to a single database; it isn't. $db_name
is merely the selected database. If you have the appropriate privileges you can either use objects from a different database (by specifying the database name as prefix) or switch the selected database as many times as you want (for which you'd use mysqli_select_db()
); the plain SQL equivalents would be:
USE shop;
SELECT *
FROM orders o
INNER JOIN crm.customers c ON o.customer_id = c.customer_id;
USE crm;
SELECT *
FROM customers;