【问题标题】:What does 'new mysqli(...);' return if error occurs?'new mysqli(...);' 是什么意思?如果发生错误返回?
【发布时间】:2018-12-14 15:12:56
【问题描述】:

我想将 mysqli 对象保存到一个变量中。如果发生错误,构造函数返回什么?我的意思是,例如,如果我传递了错误的登录名/密码/ip/dbname,我会收到一条警告消息(如果启用了警告),但变量中的值是什么?

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

我在 PHP 手册中找不到此信息。

【问题讨论】:

标签: php mysqli database-connection


【解决方案1】:

来自@Funk Forty Niner 指出的 PHP 文档。

https://secure.php.net/manual/en/mysqli.construct.php

注意:

仅面向 OO 语法:如果连接失败,仍会返回一个对象。要检查连接是否失败,请使用 mysqli_connect_error() 函数或 mysqli->connect_error 属性,如前面的示例所示。

但是,如果您像往常一样正确启用错误报告,那么如果 mysqli 无法连接到服务器,它将抛出异常并且不返回任何内容。要在打开连接之前正确启用错误报告:

<?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');

与 PHP 手册所说的相反,您永远不应该手动检查 mysqli 连接错误!

【讨论】:

    【解决方案2】:

    它仍然会返回一个 mysqli 对象,以便您可以从中获取 connect_error:

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

    结果(前两行打印多次):

    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] => )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 2020-03-07
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      相关资源
      最近更新 更多