Why does PDO generate warnings when we say that it doesn’t?

Problem

We inform the PDO of the exclusion of each problem. In some cases, it generates several warnings and only then throws an exception.

Why does this?

Duplicates?

There were no right answers to SO regarding this. The last question was PHP PDO + Exception. MySQL warning is a thing of the past? , but people simply marked it as a duplicate, and did not carefully answer.

The accepted answer does not answer why he does it and when. So I researched and will answer.

+4
source share
2 answers

set_error_handler() restore_error_handler()

public function query($sql)
{
    $retries = 0;
    $result = null;

    while (true) {
        try {
            set_error_handler(function () {
            });
            $result = $this->pdo->query($sql);
            restore_error_handler();
            break;
        } catch (Exception $e) {
            restore_error_handler();
            if (++$retries < self::RECONNECT_ATTEMPT) {
                if (strpos($e->getMessage(), 'server has gone away') !== false) {
                    $this->connect();
                    $this->getLogger()->info('Reconnect database, reason: server has gone away');
                }
            } else {
                throw $e;
            }
        }
    }
    return $result;
}
0

Source: https://habr.com/ru/post/1628316/


All Articles