-2

I'd like to save mysqli object into a variable. What does constructor return, if an error occurs? I mean if for example, I pass wrong login/pass/ip/dbname, I get a warning message (if warnings are enabled), but what value is in the variable?

<?php
    error_reporting(E_ALL ^ E_WARNING);
    
    $conn = new mysqli("bad", "bad", "so bad", "too bad, what then?");
    //what is in $conn?

I could not find this information in PHP manual.

Dharman
  • 30,962
  • 25
  • 85
  • 135
mpaw
  • 45
  • 1
  • 8

2 Answers2

2

From the PHP docs as pointed out by @Funk Forty Niner.

https://secure.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.

However, if you enable error reporting properly like you always should then if mysqli can't connect to the server it will throw an exception and return nothing. To do it properly enable error reporting before opening the connection:

<?php

error_reporting(E_ALL ^ E_WARNING);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("bad", "bad", "so bad", "too bad, what then?");
// If an error occurred then the lines below will never be executed

//VVV - $conn will always be a valid mysqli object
$conn->set_charset('utf8mb4');

Contrary to what the PHP manual says, you should never check for mysqli connection errors manually!

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

It will still return a mysqli object, so that you can get the connect_error out of it:

$conn = new mysqli("bad", "bad", "so bad", "too bad, what then?");
print_r($conn);

Results (the first two lines are printed many times):

Warning: print_r(): Couldn't fetch mysqli in /path/to/test.php on line 4 PHP
Warning:  print_r(): Couldn't fetch mysqli in /path/to/test.php on line 4 

Warning: print_r(): Couldn't fetch mysqli in /path/to/test.php on line 4 (
    [affected_rows] =>
    [client_info] =>
    [client_version] => 50011
    [connect_errno] => 2002
    [connect_error] => php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution
    [errno] =>
    [error] =>
    [error_list] =>
    [field_count] =>
    [host_info] =>
    [info] =>
    [insert_id] =>
    [server_info] =>
    [server_version] =>
    [stat] =>
    [sqlstate] =>
    [protocol_version] =>
    [thread_id] =>
    [warning_count] => )
aynber
  • 22,380
  • 8
  • 50
  • 63