跟进这里的帖子,看来我已经设法扩展了 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]:未找到基表或视图:1146 表 'xx_2011.table_not_exist' 不存在
但它返回了一个0
!为什么??我该如何解决?
谢谢。