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

查看:105
本文介绍了PHP的PDO execute()与fetch()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题,希望能有一个快速明确的答案.

I have a quick question that I hope has a quick and clear answer.

在php.com的手册上,它指出将值绑定到准备好的查询后的execute()将在成功时返回true,在失败时返回false.很简单.

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. Simple enough.

我只是想确保我清楚这一点.在execute()上返回的值对应于直接错误.例如,如果数据库在成功连接后以某种方式关闭,并且无法执行查询-或其他一些异常问题.

I just wanted to make sure I had this clear. The values returned on execute() correspond to direct errors. For instance, if the database somehow went down after a successful connect, and the query could not be executed - or some other extraordinary issue.

考虑一些代码:

    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;
        }   
    }

我相当确定这将无法按我的意愿进行.关键是要根据参数是否存在相应的值来查看数据库中是否存在t_id.在这种情况下,我需要使用$ stmt-> fetch().我这样说对吗?

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. In that case, I need to use $stmt->fetch(). Am I correct in saying that?

感谢您的帮助.

出于同样的考虑,还是放心-或者我应该说最好的做法-放置

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();

在尝试捕获内,因为PDO返回异常?

within a try-catch since PDO returns exceptions?

推荐答案

是的,您是正确的. $stmt->execute()仅在执行查询失败时返回false.它不会返回false且结果集为空.因此,您需要使用fetch()来检查结果,fetch()返回false以获得空结果集.

Yes, you are right. $stmt->execute() return false only when it failed to execute the query. It won't return false with empty result set. So you need to use fetch() to check the result, fetch() return false for empty result set.

对于异常,仅当为方法execute()等设置异常模式时,PDO才会引发异常.但是,无论是否设置了异常模式,new PDO(...)都将引发异常.

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.

这篇关于PHP的PDO execute()与fetch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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