extending PDO class: why does the method return 0 instead of error message?

313 views Asked by At

Following up on the post here, it seems that I have managed to extend the pdo class,

class database_extended extends PDO
{

    #make a connection
    public function __construct($dsn,$username,$password)
    {
        try 
        { 
            parent::__construct($dsn,$username,$password);
            //$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $e) 
        {
            # call the get_error function
            self::get_error($e);
        }
    }

    #get the number of rows in a result
    public function num_rows($query)
    {
        try 
        {
            # create a prepared statement
            $stmt = parent::prepare($query);

            # execute query 
            $stmt->execute();

            # return the result
            return $stmt->rowCount();
        } 
        catch (PDOException $e) 
        {
            # call the get_error function
            self::get_error($e);
        }
    }

    # display error
    public function get_error($e) 
    {
        $this->connection = null;
        die($e->getMessage());
    }

    # closes the database connection when object is destroyed.
    public function __destruct()
    {

    }
}

But it seems not quite right - I tested the num_rows method with a mistake in the query on purpose, so this method can return an error message,

# the host used to access DB
define('DB_HOST', 'localhost');

# the username used to access DB
define('DB_USER', 'root');

# the password for the username
define('DB_PASS', 'xx');

# the name of your databse 
define('DB_NAME', 'xx_2011');

# the data source name
define('DSN', 'mysql:dbname='.DB_NAME.';host='.DB_HOST);

include 'class_database.php';

$connection = new database_extended(DSN,DB_USER,DB_PASS);

$sql = "
    SELECT *
    FROM table_not_exist
    ORDER BY cnt_id DESC
    ";

echo $connection->num_rows($sql);

It should returns,

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'xx_2011.table_not_exist' doesn't exist

But it returns a 0 instead! Why?? How can I fix it?

Thanks.

2

There are 2 answers

0
Dan Grossman On

PDOStatement::execute returns false when the query results in an error, it doesn't throw an exception. You should probably write some code to check that return value if you want to do something with the error.

2
deceze On

Because PDOStatement::execute does not throw, it only returns false upon failure. Hence your code never enters the catch block. Should be more along the lines of this:

$stmt = parent::prepare($query);

if (!$stmt->execute()) {
    self::get_error();
}

return $stmt->rowCount();