Home > database >  When pdo exec() method will return false?
When pdo exec() method will return false?

Time:01-10

I have a database that I've build using PDO, and I am building some database tests using phpunit. However, I need to test some cases involved with pdo exec(), that returns a false or an int. What I want to know is: In which case pdo exec() will return false?

For example: I have this method that creates my database table. When my pdo exec() will be false?

public function createTable(): \PDO
    {
        try {
            $createTable = "
                            CREATE TABLE IF NOT EXISTS Transactions(
                                idTransaction int NOT NULL PRIMARY KEY AUTO_INCREMENT,
                                description varchar(255) NOT NULL,
                                price float NOT NULL,
                                category varchar(45) NOT NULL,
                                date varchar(10) NOT NULL,
                                type TINYINT NOT NULL);";

            $this->pdo->exec($createTable);
            return $this->pdo;
        } catch (\PDOException $PDOException) {
            throw new \PDOException($PDOException->getMessage());
        }
    }

CodePudding user response:

If PDO connection was not configured with param PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION (which is default behavior), exec() method will return false instead of throwing a PDOException. See this answer https://stackoverflow.com/a/8992933/6051839. In this case the last error happened will be accessible via PDO::errorCode() and PDO::errorInfo() methods, see this example https://www.php.net/manual/en/pdo.errorcode.php#refsect1-pdo.errorcode-examples.

So, to get false from exec(), just remove setting PDO::ATTR_ERRMODE attribute (if you set it now) and try to execute invalid sql, for example.

P.S. And as other commenters said, always check the result via strict comparison, since it can be 0 (which means no error, just no rows affected by query). I.e.

NOT

$result = $pdo->exec(...);
if (!$result) {// error!}

BUT

$result = $pdo->exec(...);
if ($result === false) {// error!}
  • Related