I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
If the query fails, or let’s say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
Ошибки и их обработка
PDO предлагает на выбор 3 стратегии обработки ошибок в зависимости от вашего
стиля разработки приложений.
-
PDO::ERRMODE_SILENT
До PHP 8.0.0, это был режим по умолчанию. PDO просто предоставит вам код ошибки, который
можно получить методами PDO::errorCode() и
PDO::errorInfo(). Эти методы реализованы как в объектах
запросов, так и в объектах баз данных. Если ошибка вызвана во время выполнения
кода объекта запроса, нужно вызвать метод
PDOStatement::errorCode() или
PDOStatement::errorInfo() этого объекта. Если ошибка
вызова объекта базы данных, нужно вызвать аналогичные методы у этого объекта. -
PDO::ERRMODE_WARNING
Помимо установки кода ошибки PDO выдаст обычное E_WARNING сообщение. Это может
быть полезно при отладке или тестировании, когда нужно видеть, что произошло,
но не нужно прерывать работу приложения. -
PDO::ERRMODE_EXCEPTION
Начиная с PHP 8.0.0 является режимом по умолчанию. Помимо задания кода ошибки PDO будет выбрасывать исключение
PDOException, свойства которого будут отражать
код ошибки и её описание. Этот режим также полезен при отладке, так как
сразу известно, где в программе произошла ошибка. Это позволяет быстро
локализовать и решить проблему. (Не забывайте, что если исключение
является причиной завершения работы скрипта, все активные транзакции
будут откачены.)Режим исключений также полезен, так как даёт возможность структурировать
обработку ошибок более тщательно, нежели с обычными предупреждениями PHP, а
также с меньшей вложенностью кода, чем в случае работы в тихом режиме с
явной проверкой возвращаемых значений при каждом обращении к базе данных.Подробнее об исключениях в PHP смотрите в разделе Исключения.
PDO стандартизирован для работы со строковыми кодами ошибок SQL-92 SQLSTATE.
Отдельные драйверы PDO могут задавать соответствия своих собственных кодов
кодам SQLSTATE. Метод PDO::errorCode() возвращает одиночный
код SQLSTATE. Если необходима специфичная информация об ошибке, PDO предлагает
метод PDO::errorInfo(), который возвращает массив, содержащий
код SQLSTATE, код ошибки драйвера, а также строку ошибки драйвера.
Пример #1 Создание PDO объекта и установка режима обработки ошибок
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// PDO выбросит исключение PDOException (если таблица не существует)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>
Результат выполнения данного примера:
Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testdb.wrongtable' doesn't exist in /tmp/pdo_test.php:10 Stack trace: #0 /tmp/pdo_test.php(10): PDO->query('SELECT wrongcol...') #1 {main} thrown in /tmp/pdo_test.php on line 10
Замечание:
Метод PDO::__construct() будет всегда бросать исключение PDOException,
если соединение оборвалось, независимо от установленного значенияPDO::ATTR_ERRMODE
.
Пример #2 Создание экземпляра класса PDO и установка режима обработки ошибок в конструкторе
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));// Следующий запрос приводит к ошибке уровня E_WARNING вместо исключения (когда таблица не существует)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>
Результат выполнения данного примера:
Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in /tmp/pdo_test.php on line 9
There are no user contributed notes for this page.
I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
If the query fails, or let’s say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
Often it can be quite hard to debug SQL errors when using PHP since PHP will often throw a generic error that doesn’t really help you diagnose the situation. Other times you may not want to allow PHP errors to be shown. A quick way to debug PDO SQL errors is to use the or die function. “or die” works by executing the SQL query and if it fails to execute it will “die” and output the contents of the function. This is quite similar to a try catch block.
In order to output the PDO error you will need to get the error info from the statement object. To implement this function simply add the or die code to the end of the $stmt->execute code.
$stmt = $db->prepare($sql); $stmt->execute($array) or die(print_r($stmt->errorInfo(), true));
The critical part of this code is the call to the method “errorInfo on the stmt class. There are lots of different types of SQL errors that can happen. A lot of time time, if you are developing code, the cause will be the query you have written. This method will allow you to dump the entire error response that is returned from the DB.
Log PDO and SQL errors internally
This should go without saying, but I will say it anyway. You should never output SQL or PDO errors onto the page in a live scenario. These error messages can expose highly sensitive information about your web site, DB and or server. If this information gets into the wrong hands, you could find yourself with a hacked website.
The code snippet above will dump the entire error onto the web page. Very useful in development, but not in production. Please be careful and use an internal logging system to keep track of database errors on a production website.
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;
}
}
}
?>