I have a PHP application which connects to a database.
The connection details (hostname,username,password,etc.) are supplied by the user. The problem is that when the user enters a non-exsisting hostname, I get the following warning:
Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed
How do I handle this error? I am already using try-catch and it handles other exceptions perfectly (wrong username or password), but not this one.
Here is my code:
backend.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));
}
}
?>
library.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;
}
}
?>