php - 扩展 PDO 类 : why does the method return 0 instead of error message?

标签 php mysql pdo extends mysql-error-1146

跟进post在这里,我似乎已经成功地扩展了 pdo 类,

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

    }
}

但这似乎不太正确 - 我故意在查询中测试了 num_rows 方法,因此该方法可以返回错误消息,

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

它应该返回,

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

但它返回的是0!为什么??我该如何修复它?

谢谢。

最佳答案

因为 PDOStatement::execute 不会抛出,所以它仅在失败时返回false。因此,您的代码永远不会进入 catch block 。应该更多的是这样的:

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

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

return $stmt->rowCount();

关于php - 扩展 PDO 类 : why does the method return 0 instead of error message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5176061/

相关文章:

PHP - 使用 LDAP 身份验证创建登录页面

Mysql多表UPDATE第一条记录

MySQL MAX_JOIN_SIZE 错误!需要优化查询

mysql - PDO更新语句不更新记录

php - 在 Mac OSX 上启用 PHP pdo_odbc 扩展

PHP 使用 PDO 检查远程数据库的查询是否返回数据

php - 如何从 PHP MySQL 中的 3 个以上表中进行选择

php - 查询返回 false

php - 使用for循环在php中生成sql查询

mysql - 主键和索引在同一个表上