Home >Database >Mysql Tutorial >How to Make PDO Report Database Connection Errors?

How to Make PDO Report Database Connection Errors?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 16:23:02926browse

How to Make PDO Report Database Connection Errors?

PDO Connection Testing

Query:

Can PDO be utilized to validate and invalidate database connections? A PHP script is provided that attempts to connect to a database but stalls instead of reporting a connection error.

Solution:

In order for PDO to properly report connection errors, it is necessary to set the error mode explicitly:

try {
    $dbh = new pdo(
        'mysql:host=127.0.0.1:3308;dbname=axpdb',
        'admin',
        '1234',
        array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
    );
    die(json_encode(array('outcome' => true)));
} catch (PDOException $ex) {
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}

By setting the ERRMODE attribute to EXCEPTION, PDO will throw an exception when a connection error occurs. This allows for error handling and avoids the script from timing out.

Additional Information:

  • [Using MySQL with PDO](https://www.php.net/manual/en/ref.pdo-mysql.php)
  • [Errors and Error Handling](https://www.php.net/manual/en/pdo.error-handling.php)

The above is the detailed content of How to Make PDO Report Database Connection Errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn