0
當我試圖用database->Select
測試我的try-catch塊時,我期待在嘗試回顯PDO語句時捕獲異常,但它告訴我錯誤未被捕獲。php嘗試捕獲不捕獲異常
Catchable fatal error: Object of class PDOStatement could not be converted to string
我不明白我在做什麼錯在這裏。
下面是代碼:
class database{
private $conn;
private $sqlError;
public function __construct() {
$server = "localhost";
$username = "user";
$pass = "password";
$database = 'dbname';
$dsn = sprintf('mysql:dbname=%s;host=%s', $database, $server);
try {
$this->conn = new PDO($dsn, $username, $pass);
} catch (Exception $exc) {
$this->sqlError = 'SQL Error: ' . $exc->getCode();
}
}
public function Select($query, $values=array()) {
unset($this->sqlError);
try {
$qry = $this->conn->prepare('select ' . $query);
echo $qry; //invalid operation, I expect exception to be thrown
$qry->execute($values);
$result = $qry->fetchAll(PDO::FETCH_OBJ);
$error = $qry->errorInfo();
if ($error[1]) {
$this->sqlError = 'SQL Error: ' . $error[1];
}
return $result;
} catch (Exception $exc) {
$this->sqlError = 'SQL Error: ' . $exc->getCode();
}
}
}
'echo $ qry'是故意嘗試拋出一個異常,但我現在明白與你的好解釋不同。 – andrew