I am trying to write a small class so I can use it to connect to my databases But I am havinf an issue that PDO is not displaying an error.
What I am trying to do is to display mysql error when the query fails so I know what is the error and fix it.
In my call I have 4 methods where i need to catch mysql errors.
startConnection()
getOneResult()
processQuery()
getDataSet()
This is my current class Can some one please show me how to display the mysql error. Note I tried to use try catch to catch the error but that did not work for me.
Thanks for your help
<?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;
}
}
}
?>