pdo catch and output mysql errors

后端 未结 3 470
时光说笑
时光说笑 2021-02-07 20:52

Still trying to get my head around pdo.

I have an insert statement that is executed with pdo. insert works great however if there is an error I would like it displayed t

相关标签:
3条回答
  • 2021-02-07 21:11

    You should use this:

    return $exception->getMessage();
    

    See the page on the documentation of Exception class:

    http://www.php.net/manual/en/exception.getmessage.php

    0 讨论(0)
  • 2021-02-07 21:14

    By default PDO is not in a state that will display errors. you need to provide the following in your DB connection

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

    More info can be seen Here

    0 讨论(0)
  • 2021-02-07 21:25

    1.Add ERRMODE_EXCEPTION mode after your db connection:

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

    2.And than you must use try{} catch{} method for all your mysql query. Like this:

    try {
        $SQL = "DELETE FROM items WHERE item_id=:item_id";
        $m = $dbh->prepare($SQL);
        $m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
        $m->execute();
        //success
        $return = "Your success message.";
    }
    catch (PDOException $e) {
        //error
        $return = "Your fail message: " . $e->getMessage();
    }
    
    0 讨论(0)
提交回复
热议问题