跟进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/