Tadmas
Tadmas

Reputation: 6368

Using default values for mysqli constructor fails

I am trying to connect to a database using the default values for the mysqli constructor, which is documented to be:

The reason I want to use the defaults is so I can have the credentials in the config file instead of scattered through my code. However, when I pass no values, the connection succeeds but then subsequent queries fail with no error.

$db = new mysqli();
if ($db->connect_errno) die("Connect failed: " . $db->connect_error);
if ($rs = $db->query("select user();") or die("Query failed: " . $db->error)) {
  $row = $rs->fetch_row();
  echo $row[0];
  $rs->close();
}

This outputs:

Query failed:

That means the connection succeeded, but any query fails with an error. (Other actions, such as select_db, fail the same way.)

Interestingly, I can fix it by changing the first line to:

$db = new mysqli(ini_get("mysqli.default_host"),
                 ini_get("mysqli.default_user"),
                 ini_get("mysqli.default_pw"));

... but I'd prefer to not have to type out the default values everywhere I need a database connection. What am I doing wrong? Is there a way to use the mysqli constructor with no arguments?

Upvotes: 3

Views: 484

Answers (1)

Tadmas
Tadmas

Reputation: 6368

While writing this question, I happened to scroll down the documentation page and noted the following:

Note: Calling the constructor with no parameters is the same as calling mysqli_init().

Looking up the mysqli_init documentation, it says:

Note: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Therefore, the fix is to change the first line from:

$db = new mysqli();

To:

$db = new mysqli();
$db->real_connect();

I would have expected in that scenario that mysqli_error would have returned something like "not connected" instead of an empty string. That's a bit counter-intuitive, but at least it's somewhat documented.

Upvotes: 3

Related Questions