Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress PHP Warnings with PDO

I've tried hard to by-pass PDO warning but without success.

Here's my code (file names and parameters are obfuscated with XXXXXX):

try {
    ini_set('pdo_mysql.debug' , '0');

    $pdo = new PDO("mysql:host=XXXXXX;port=XXXXXX;dbname=XXXXXX", 'XXXXXX', 'XXXXXX', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->exec('SET session wait_timeout=1');

    $pdo->query('SELECT 1');
    echo "SELECT 1\n";

    sleep(2);

    $pdo->query('SELECT 1');
    echo "SELECT 1\n";
} catch (Exception $e) {
    echo "Exception: {$e->getMessage()}\n";
}

I've tried with and w/o ini_set, I've tried with PDO error mode in constuctor, in parameters or both (like in this example), I've also tried with named host or its IP address.

SET wait_timeout and sleep are here just to help testing

Nothing to do, I always get the same result:

SELECT 1
PHP Warning:  PDO::query(): MySQL server has gone away in XXXXXX/test.php on line 19
PHP Stack trace:
PHP   1. {main}() XXXXXX/test.php:0
PHP   2. PDO->query() XXXXXX/test.php:19
PHP Warning:  PDO::query(): Error reading result set's header in XXXXXX/test.php on line 19
PHP Stack trace:
PHP   1. {main}() XXXXXX/test.php:0
PHP   2. PDO->query() XXXXXX/test.php:19
Exception: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

As you can see, Exception has been catched (last line) and it's catched as well with catching PDOException or Throwable, with or without backslash.

I just wish to suppress PHP Warning, and normally it should not appear due to ERRMODE_EXCEPTION parameter but this warning always "pops".

A few things about the context:

  • this part of code is just for testing, the whole code is in a class called for a lot of things and I cannot just don't log PHP Warnings
  • in production context we just have the PHP Warning (not the stack trace)
  • code is running in PHP v7.0 on Linux server
  • I don't want to use the @ to hide Warnings

Thanks

like image 889
Unkl Benz Avatar asked Jan 26 '26 16:01

Unkl Benz


1 Answers

I think your exception gets caught ok but you need to change your settings with regards to error display:

ini_set('display_errors', 0);

You can also set this in php.ini

like image 61
Kasia Gogolek Avatar answered Jan 28 '26 08:01

Kasia Gogolek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!