pdo catch and output mysql errors

后端 未结 3 466
时光说笑
时光说笑 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: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();
    }
    

提交回复
热议问题