在这里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]:基表或视图 未找到:1146表 'xx_2011.table_not_exist'没有 存在
但它会返回0
!为什么??我该如何解决?
感谢。
答案 0 :(得分:2)
由于PDOStatement::execute
没有throw
,因此只有在失败时才会返回false
。因此,您的代码永远不会进入catch
块。应该更加符合这一点:
$stmt = parent::prepare($query);
if (!$stmt->execute()) {
self::get_error();
}
return $stmt->rowCount();
答案 1 :(得分:0)
PDOStatement::execute
返回false,它不会引发异常。如果你想对错误做些什么,你应该写一些代码来检查返回值。