Cliff_Cleet
Cliff_Cleet

Reputation: 211

What is the difference between mysqli_connect queries

what is the difference between

  1. $link = mysqli_connect($dbhost, $dbuser, $dbpass);

  2. $conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die(mysqli_error($link));

Upvotes: 1

Views: 416

Answers (2)

Dharman
Dharman

Reputation: 33315

The only difference between these two lines is that if you have mysqli error reporting switched off and the connection cannot be established, then the first mysqli_connect will return null and continue as if nothing happened, whereas the second one will kill the script and leak your sensitive credentials.

Do not use either one. The proper way to connect via mysqli class is this:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'user', 'pass', 'db');
$link->set_charset('utf8mb4'); // always set the charset

Three lines only, and no die or if statements.

First, you need to enable error reporting for mysqli, then you create the instance of this class, and lastly you set the correct charset.

Upvotes: 1

Aman Kumar
Aman Kumar

Reputation: 4547

$link = mysqli_connect($dbhost, $dbuser, $dbpass);

$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die(mysqli_error($link));

mysqli_error : Returns a string description of the last error

Above $link and $conn both variables are same carry connection object but in second $conn case when there is some error then connection die and generate mysqli last error

Upvotes: 1

Related Questions