Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I raise PDOException?

Tags:

exception

php

pdo

This code works fine, but I'll want to handle exception if any thing goes wrong, so I deliberately made a syntax error in the query but nothing happens. Below is the code

try {
    $sql = "INSERT INTO journals (topic, author, ) VALUES ('$topic', '$authors', ')";
    echo "1st";
    $lecturers_db->query($sql);
    echo "second";
} catch(PDOException $e) {
    echo $e->getMessage();
    echo $msg = "Error!";
} 

Without the obvious syntax error, the code works fine but with the syntax error, nothing happens, all the code in the try block executes and the code in the catch block never executes.

I want to raise an exception, please how do I do it here, thanks for any help.

like image 206
Chibuzo Avatar asked Jun 15 '12 12:06

Chibuzo


People also ask

How do you get PDOException?

To catch a PDOException object and handle the associated error: Wrap the call to the PDO constructor in a try block. Following the try block, include a catch block that catches the PDOException object.

What does PDOException mean?

PHP Data Objects (or PDO ) are a collection of APIs and interfaces that attempt to streamline and consolidate the various ways databases can be accessed and manipulated into a singular package. Thus, the PDOException is thrown anytime something goes wrong while using the PDO class, or related extensions.

How to get PDO error?

PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object.


2 Answers

Be sure to set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, as soon as you init your pdo object:

$lecturers_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

After that, any failed queries will raise an exception

like image 142
marcelog Avatar answered Sep 22 '22 20:09

marcelog


Exceptions are thrown. Syntax errors in code != Exceptions.

<?php 
    try {
        $code = 12;
        throw new PDOException('Message', $code );
    } catch (PDOException $e) {

    }
?>

However, from the maual:

You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

My advice is to throw either a general exception, or to write your own custom exception to handle your error.

like image 27
Jeff Lambert Avatar answered Sep 24 '22 20:09

Jeff Lambert