Home > Database > Mysql Tutorial > How to Retrieve SQL Errors from PDO Prepared Statements in PHP?

How to Retrieve SQL Errors from PDO Prepared Statements in PHP?

Barbara Streisand
Release: 2024-12-15 20:47:17
Original
832 people have browsed it

How to Retrieve SQL Errors from PDO Prepared Statements in PHP?

Retrieving SQL Errors in PDO/Prepare in PHP

To check for intentional errors in MySQL queries using the prepare() method in PDO PHP, follow these steps:

1. Set the Error Mode Attribute

Set the error mode attribute to PDO::ERRMODE_EXCEPTION using the setAttribute() method to enable exception handling. This will cause the prepare method to throw an exception if an error occurs:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Copy after login

2. Disable Emulation

Disable PDO::ATTR_EMULATE_PREPARES by setting it to false. This is necessary because the MySQL server may not evaluate the prepared statement until execution, making it harder to detect errors:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Copy after login

Example:

The following code prepares the query "SELECT * FROM c6ode" and throws an exception if the table c6ode does not exist:

try {
    $st = $db->prepare("SELECT * FROM c6ode");
} catch (PDOException $e) {
    // Handle the exception and display the error message
}
Copy after login

Exception Output:

Executing the above code (with c6ode not existing) will print an exception message indicating that the table does not exist:

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

The above is the detailed content of How to Retrieve SQL Errors from PDO Prepared Statements 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