データベースに接続するために使用できるように小さなクラスを作成しようとしていますが、PDOがエラーを表示しないという問題があります。
私がやろうとしているのは、クエリが失敗したときにmysqlエラーを表示することです。これにより、エラーが何であるかがわかり、修正できます。
私の呼び出しでは、mysqlエラーをキャッチする必要がある4つのメソッドがあります。
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;
}
}
}
?>