Home >Database >Mysql Tutorial >How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?

How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 06:51:09517browse

How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?

How to retrieve query errors from PDO prepare() in PHP?

Problem:

Consider the following PHP code:

$st = $db->prepare("SELECT * FROM c6ode");

How can you obtain the intended MySQL error for the query in this instance?

Solution:

To retrieve error information from prepare(), you must:

  1. Set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
  2. Disable the PDO::ATTR_EMULATE_PREPARES feature, as it prevents the MySQL server from immediately processing the statement.

Here's an example:

<?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 (?)');

This code will throw an exception and print the following error message:

SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist

The above is the detailed content of How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?. 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