简体   繁体   English

PHP的PDO执行()与fetch()?

[英]PHP's PDO execute() vs. fetch()?

I have a quick question that I hope has a quick and clear answer. 我有一个简短的问题,我希望得到一个快速而明确的答案。

On php.com's manual, it states that execute() after binding the values to a prepared query will return true on success and false on failure. 在php.com的手册中,它声明在将值绑定到准备好的查询之后,execute()将在成功时返回true,在失败时返回false。 Simple enough. 很简单。

I just wanted to make sure I had this clear. 我只是想确保我清楚这一点。 The values returned on execute() correspond to direct errors. execute()返回的值对应于直接错误。 For instance, if the database somehow went down after a successful connect, and the query could not be executed - or some other extraordinary issue. 例如,如果数据库在成功连接后以某种方式失败,并且无法执行查询 - 或其他一些特殊问题。

Consider some code: 考虑一些代码:

    protected function territoryCheck($numberOut)
    {
        $this->numberOut = $numberOut;

        //Execute test
        $this->checkConnect();
        $stmt = $this->dbh->prepare("SELECT t_id FROM Territory WHERE t_id = :param1")
        $stmt->bindParam(':param1', $this->numberOut);
        $stmt->execute();

        //Determine value of test
        if($stmt == FALSE)
        {
            return FALSE;
        }   
    }

I am rather sure that this will not operate as I want. 我相信这不会按我的意愿运作。 The point is to see if t_id exists in the database based on whether there is a corresponding value to the parameter. 关键是要根据参数是否存在相应的值来查看数据库中是否存在t_id。 In that case, I need to use $stmt->fetch(). 在这种情况下,我需要使用$ stmt-> fetch()。 Am I correct in saying that? 我说的是对的吗?

Any help is appreciated. 任何帮助表示赞赏。

Edit: Along the same lines, would it be prudent - or I should say best practice - to put 编辑:沿着同样的路线,谨慎 - 或者我应该说最好的做法 - 放

//Execute test
        $this->checkConnect();
        $stmt = $this->dbh->prepare("SELECT t_id FROM Territory WHERE t_id = :param1")
        $stmt->bindParam(':param1', $this->numberOut);
        $stmt->execute();

within a try-catch since PDO returns exceptions? 在PDO返回异常后的try-catch中?

Yes, you are right. 是的,你是对的。 $stmt->execute() return false only when it failed to execute the query. $stmt->execute()仅在无法执行查询时返回false It won't return false with empty result set. 使用空结果集时,它不会返回false So you need to use fetch() to check the result, fetch() return false for empty result set. 所以你需要使用fetch()来检查结果, fetch()为空结果集返回false

And for the exceptions, PDO will throw exception only when you set the exception mode for the methods execute() etc. But new PDO(...) will throw exception no matter whether the exception mode is set. 对于异常,只有在为方法execute()等设置异常模式时,PDO才会抛出异常。但无论是否设置了异常模式, new PDO(...)都将抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM