9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PDOの例外をcatchする

9
Posted at

PHPからMySQLを扱いたい時にはPDOを使う.
SQL文を実行して失敗した時、try~catchの中に入らない.なぜ.

調べてみたところ、PDOはデフォルトで例外を吐かないよう.

デフォルトのエラーモードが PDO::ERRMODE_SILENTになっているため、例外を吐くように変更.

$db = new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

もしくは

$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

これで PDOExceptionを吐くのでcatchできるようになる

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?