3

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

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.

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. In that case, I need to use $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?

Mlagma
  • 1,240
  • 2
  • 21
  • 49

1 Answers1

2

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.

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.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Which version would utilizes the new PDO? One reference work in particular states PHP PDO triggers errors in the form of an exception - and it simply states PHP 5. – Mlagma Sep 19 '12 at 03:31