Home > Backend Development > PHP Tutorial > How Can I Retrieve PDO Prepare() Query Errors in PHP?

How Can I Retrieve PDO Prepare() Query Errors in PHP?

Barbara Streisand
Release: 2024-12-06 22:40:12
Original
214 people have browsed it

How Can I Retrieve PDO Prepare() Query Errors in PHP?

Retrieving Query Errors from prepare() in PDO PHP

When using PDO PHP to prepare a query, it's essential to check for any potential errors. By default, PDO doesn't throw exceptions for errors encountered during query preparation. To enable error handling, you can leverage the PDO::ATTR_ERRMODE attribute.

Solution

  • Set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION: By setting this attribute, prepare() will throw an exception if an error occurs.
  • Disable PDO::ATTR_EMULATE_PREPARES: To ensure the MySQL server processes the query during prepare(), disable this attribute. Emulation sometimes prevents the server from detecting errors until query execution.

Example:

$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 (?)');
Copy after login

If the provided query contains invalid syntax, PDO will throw an exception with the following information:

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

The above is the detailed content of How Can I Retrieve PDO Prepare() Query Errors in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template