You need to set the error mode attribute PDO::ATTR_ERRMODE
to PDO::ERRMODE_EXCEPTION
.
And since you expect the exception to be thrown by the prepare()
method, you should disable the PDO::ATTR_EMULATE_PREPARES
feature. Otherwise the MySQL server doesn’t “see” the statement until it’s executed.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
prints (or logs, depends on the PHP settings)
SQLSTATE[42S02]: Base table or view not found:
1146 Table 'test.doesnotexist' doesn't exist