PHP PDO: Displaying errors

前端 未结 4 2035
长情又很酷
长情又很酷 2021-01-21 11:49

Do I need to use the try and catch block to display errors with PHP\'s PDO extension?

For example, with mysql you can usally do something like:

if ( ! $q         


        
相关标签:
4条回答
  • 2021-01-21 12:31

    PDO by default supports it's own Exception Class, PDOException.

    There should be no reason why you cannot use:

    try{
        $query = $db->prepare(...);
        if( !$query ){
            throw new Exception('Query Failed');
        }
    }
    catch(Exception $e){
        echo $e->getMessage();
    }
    

    The reason I only catch Exception is because PDOException is a child of Exception. Catching the Parent will catch ALL children.

    0 讨论(0)
  • 2021-01-21 12:38

    If you don't want to use a try catch statement, you still can use this kind of code :

    $query = $db->prepare("SELECT * FROM table");
    if(!$query->execute()) {
       print_r($query->errorInfo());
    }
    
    0 讨论(0)
  • 2021-01-21 12:44
    public static function qry($sql) {
        try {
        $statement = $db_handle->prepare($sql);
        $retval = $statement->execute();
        if($statement->rowCount() >= 1) { 
            //do something               
        }else {
        $errors = $statement->errorInfo();
        echo $errors[2] . ", " . $errors[1] . " ," . $errors[0];
    }
    } catch (Exception $e) {
    echo $e->getMessage();
    }        
    }
    
    0 讨论(0)
  • 2021-01-21 12:48

    You can choose what PDO does with errors via PDO::ATTR_ERRMODE:

    $pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Raise E_WARNING.
    $pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // Sets error codes.
    // or
    $pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // throws exception
    
    0 讨论(0)
提交回复
热议问题