【发布时间】:2017-10-24 18:35:07
【问题描述】:
我有一个连接到数据库的 PHP 应用程序。
连接详细信息(主机名、用户名、密码等)由用户提供。问题是当用户输入一个不存在的主机名时,我收到以下警告:
警告:mysqli::mysqli(): php_network_getaddresses: getaddrinfo 失败
我该如何处理这个错误?我已经在使用 try-catch 并且它可以完美地处理其他异常(错误的用户名或密码),但不是这个。
这是我的代码:
后端.php
<?php
// Library setup
require_once "instlib.php";
$lib = new installer;
// Header
header('Content-Type: application/json; Charset=UTF-8');
try {
$lib->create_mysqli(array(
"host" => "a",
"user" => "b",
"pass" => "c",
"database" => "",
"port" => "3306"
));
echo $lib->build_response("AWESOME!", true);
} catch (Exception $e) {
echo $lib->build_response($e->getMessage(), false);
}
?>
instlib.php
<?php
require_once 'library.php';
class installer extends nncms
{
public function build_response($response = "", $success, $extra = array())
{
return json_encode(array_merge(array('success' => $success, 'response' => $response),$extra));
}
}
?>
库.php
<?php
class nncms
{
var $mysqli;
public function create_mysqli($config)
{
// Set MySQLi to throw expection instead of warning
mysqli_report(MYSQLI_REPORT_STRICT);
// Connection setup
$mysqli = new mysqli(
$config["host"],
$config["user"],
$config["pass"],
$config["database"],
$config["port"]
);
$mysqli->set_charset('utf8mb4');
// In case of an error that somehow didn't throw an exception
if ($mysqli->connect_errno)
throw new Exception("Connection error: ".$mysqli->connect_error);
// Set MySQLi object of class
$this->mysqli = $mysqli;
}
}
?>
【问题讨论】: