// Set up a PDO connection $conn = new PDO('mysql:host=localhost;dbname=mydatabase', $username, $password); // Attempt a query that will fail $result = $conn->query('SELECT * FROM nonexistent_table'); // Check if the query returned false (indicating an error) if ($result === false) { // Get the error message using lastErrorMsg $error = $conn->lastErrorMsg(); // Output the error message for debugging echo "Error: $error"; }
// Set up a PDO connection $conn = new PDO('mysql:host=localhost;dbname=mydatabase', $username, $password); try { // Attempt a query that will cause an exception $conn->exec('INSERT INTO mytable (col1, col2) VALUES (1, 2, 3)'); } catch (PDOException $e) { // Catch the exception and get the error message using lastErrorMsg $error = $conn->lastErrorMsg(); // Output the error message for debugging echo "Error: $error"; }In this example, we attempt to execute an `INSERT` query with three values instead of two, causing a PDOException to be thrown. We catch the exception and then use `lastErrorMsg` to retrieve the error message and output it to the screen. Based on the use of `$conn` and the PDO-specific error handling, it can be determined that this code is part of the PDO (PHP Data Objects) package/library.