我想写一个小类,以便我可以使用它来连接到我的数据库但是我有一个问题,PDO不显示错误。如何在连接类中使用PDO时显示mysql错误?
我想要做的是在查询失败时显示mysql错误,所以我知道错误是什么并修复它。
在我的电话中,我有4个方法,我需要捕获mysql错误。
startConnection()
getOneResult()
processQuery()
getDataSet()
这是我当前类 可有一个人请告诉我如何显示MySQL错误。注意我尝试使用try catch来捕捉错误,但这对我没有用。
感谢您的帮助
<?php
class connection {
private $connString;
private $userName;
private $passCode;
private $server;
private $pdo;
private $errorMessage;
private $pdo_opt = array (
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
function __construct($dbName, $serverName = 'localhost'){
//sets credentials
$this->setConnectionCredentials($dbName, $serverName);
//start the connect
$this->startConnection();
}
function startConnection(){
$this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);
if(! $this->pdo){
$this->errorMessage = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
$this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';
echo $this->getError();
}
}
//this will close the PDO connection
public function endConnection(){
$this->pdo->close;
}
//return a dataset with the results
public function getDataSet($query, $data = NULL)
{
$cmd = $this->pdo->prepare($query);
$cmd->execute($data);
return $cmd->fetchAll();
}
//return a dataset with the results
public function processQuery($query, $data = NULL)
{
$cmd = $this->pdo->prepare($query);
return $cmd->execute($data);
}
public function getOneResult($query, $data = NULL){
$cmd = $this->pdo->prepare($query);
$cmd->execute($data);
return $cmd->fetchColumn();
}
public function getError(){
if($this->errorMessage != '')
return $this->errorMessage;
else
return true; //no errors found
}
//this where you need to set new server credentials with a new case statment
function setConnectionCredentials($dbName, $serv){
switch($serv){
case 'NAME':
$this->connString = 'mysql:host='.$serv.';dbname='.$dbName.';charset=utf8';
$this->userName = 'user';
$this->passCode = 'password';
break;
default:
$this->connString = 'mysql:host=localhost;dbname=rdi_cms;charset=utf8';
$this->userName = 'user';
$this->passCode = 'pass!';
break;
}
}
}
?>
你能粘贴你如何使用try/catch语句,你在它抓到什么异常类型?另外,放置try/catch块的位置很重要? – Alexey 2013-03-25 18:30:49
你用来测试什么代码? – 2013-03-25 19:09:01