PHP PDO: Displaying errors

前端 未结 4 2044
长情又很酷
长情又很酷 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.

提交回复
热议问题