我应该在pdo php中检查执行操作的返回值吗 [英] Should I check the return value of an execute operation in pdo php

查看:60
本文介绍了我应该在pdo php中检查执行操作的返回值吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在注册系统上工作了一段时间.与db交互的数据非常敏感,因此我尝试特别注意细节. 这是我如何插入的示例.

I have been working on a registration system for a while. The data interacting with db is pretty sensitive so I'm trying to pay extra attention to details. This is an example of how I do inserts.

    try{
        $query="INSERT INTO account (user_id,password,salt) VALUES (:user_id,:password,:salt)";
        $stmt=$db->prepare($query);
        $params=array(':user_id'=>$userId,':password'=>$password,':salt'=>$salt);
        $result=$stmt->execute($params);
        if(!$result){
           $db->rollBack();
           doStaff();
        }
    }
    catch(PDOException $e){
       $db->rollBack();
       doStaff();
    }

我想知道是否存在执行操作的结果返回false但pdo不会引发异常的情况?我应该同时检查它们还是我偏执?

I was wondering if there is any scenario that the result of an execute operation returns false but pdo does not throw exception? Should I check them both, or am I being paranoid?

推荐答案

答案是肯定的.

如果您尝试做完全不可能的事情(即使用错误的主机名连接到数据库,使用错误的用户名或密码进行身份验证等),则会引发PDOException.但是,如果您的SQL中仅存在语法错误或未定义的引用,请 PDOStatement :: execute 将静默返回false.如果要检查这些错误并回滚更改,则一定要确保execute返回true.

A PDOException will be raised if you try to do something entirely impossible (i.e. connect to database with an incorrect hostname, authenticate with an incorrect username or password, etc.). However, if there is simply a syntax error or undefined reference in your SQL, PDOStatement::execute will silently return false. If you want to check for these errors and roll back the changes, you should certainly make sure that execute returns true.

但是,您可以更改此行为, SQL错误显示为异常:

However, instead of this, you can change this behavior so that SQL errors appear as exceptions:

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

然后,您的代码中只有一个catch语句就足够了.

Then, a single catch statement in your code will suffice.

这篇关于我应该在pdo php中检查执行操作的返回值吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆