我正在尝试编写一个小类,以便可以使用它来连接到我的数据库但是我遇到了一个问题,即 PDO 没有显示错误。
我要做的是在查询失败时显示 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;
}
}
}
?>