When MySQL database imports data, warnings often appear.
These warnings are easy to be ignored.
I suddenly want to see what the warnings are when I get to the data today.
MySQL view warning command
show warnings;
The command is very concise, and the general warning is like this when I check it.
1.
Warning | 1265 | Data truncated for column ‘title’ at row 1265
This warning is that the field length is not enough,
the imported data is automatically cropped by the system.
2.
| Warning | 1366 | Incorrect string value: ‘xB5xDAxB6xFExBDxEC...‘ for column ‘Journal title’ at row 1444 |
This is the wrong character set of the data.
For the second one, you need to modify the character set of the database or the txt encoding format of the imported data.
3.
| Warning | 1366 | Incorrect integer value: ‘‘ for column ‘work number’ at row 13 |
This is to insert empty data, if the field allows null values, you can ignore these warnings.
4.
| Warning | 1262 | Row 11 was truncated; it contained more data than there were input columns |
This is a redundant column of imported data.
The MySQL warning is easy to understand, and it is easy to modify the table after the warning message.
Summary: in this tutorial, you will learn how to use the MySQL SHOW ERRORS
statement to display error information generated by a query.
Introduction to MySQL SHOW ERRORS
statement
The SHOW ERRORS
is a diagnostic statement that displays information for errors.
The SHOW ERRORS
is similar to the SHOW WARNINGS
except that it shows only errors, not warnings and notes.
The following SHOW ERRORS
displays all errors:
SHOW ERRORS;
Code language: SQL (Structured Query Language) (sql)
To limit the number of errors to return, you use the SHOW ERRORS LIMIT
statement:
SHOW ERRORS [LIMIT [offset,] row_count];
Code language: SQL (Structured Query Language) (sql)
The LIMIT
clause has the same meaning as for the SELECT
statement.
To get the total number of errors, you use the following form of the SHOW ERRORS
statement:
SHOW COUNT(*) ERRORS;
Code language: SQL (Structured Query Language) (sql)
Or you can select it from the system variable @@error_count
:
SELECT @@error_count;
Code language: SQL (Structured Query Language) (sql)
MySQL SHOW ERRORS
statement example
This statement returns id from the products
table in the sample database:
SELECT id FROM products;
Code language: SQL (Structured Query Language) (sql)
However, the products
table does not have the id
column.
To show the error, you use the SHOW ERRORS
statement:
SHOW ERRORS;
Code language: SQL (Structured Query Language) (sql)
To get the total number of errors, you use the error_count
variable:
SELECT @@error_count;
Code language: SQL (Structured Query Language) (sql)
In this tutorial, you will have learned how to use the MySQL SHOW ERRORS
statement to display error information.
Was this tutorial helpful?
При отладке готового сайта на сервере просто необходимо бывает включить вывод ошибок PHP. Мало ли что может вылезти, так лучше ознакомиться с этим заранее. Ну, или узнать почему же вроде рабочий сайт вдруг не запускается на сервере.
Сделать это не сложно, просто добавьте следующие строки в файл .htaccess в корне сайте.
php_value error_reporting -1
php_flag display_errors on
php_flag display_startup_errors on
php_flag ignore_repeated_source off
php_flag ignore_repeated_errors off
php_flag track_errors on
php_flag log_errors on
php_flag mysql.trace_mode on
Скачать готовый файл .htaccess.
Приведу краткую справку по этим параметрам.
error_reporting — указывает, какие ошибки выводятся по уровню значимости. При значении директивы -1 отображаются все ошибки.
display_errors — включает опцию для вывода ошибок на экран вместе с остальным кодом.
display_startup_errors — включает опцию вывода ошибок, возникающих при запуске PHP, когда еще не работает директива display_errors.
ignore_repeated_errors — игнорирование повторяющихся ошибок (ошибка в том же файле и той же строке).
ignore_repeated_source — игнорирование источника ошибок при пропуске повторяющихся сообщений. Если опция включена, то повторяющиеся ошибки не будут выводится вне зависимости от того, в каком файле они произошли.
track_errors — при включении этой директивы текст последней ошибки помещается в переменную $php_errormsg.
log_errors — включает сохранение ошибок в лог. По умолчанию это журнал ошибок сервера, но назначение можно изменить директивой error_log.
mysql.trace_mode — включает трассировку ошибок MySQL.
Если хочется сохранять лог-ошибок в отдельный файл, то добавьте в .htaccess следующую строку:
php_value error_log /путь_к_сайту/php-errors.log
Путь к сайту можно узнать, загрузив на сервер php-файл со следующим содержимым и открыв его в браузере.
<?php
echo $_SERVER['DOCUMENT_ROOT'];
?>
Скачать готовый php-файл.
Конечно, ненужные вам директивы вполне можно исключить. По большей степени, необходимыми для отладки являются только первые три параметра: error_reporting, display_errors и display_startup_errors.
Приветствую всех читателей! Сегодня я хочу вам рассказать про функции вывода ошибок, которые используются в MySQLi. Бывают такие моменты, что запрос к базе завершается ошибкой, и ошибка выводится на экран не в обычном виде. То есть ошибка ссылается просто на строку в файле php, в котором происходит этот запрос к базе. Вот как раз для вывода нормальной информации об ошибках и используются функции MySQLi.
И так приступим.
За предоставление информации об ошибках, в MySQLi используются функции mysqli_errno и mysqli_error. Но эти функции не используются для получения информации об ошибках, возникших в функции соединения с базой данных. То есть эти функции можно использовать только для выявления ошибок, которые возникают в выполнении запросов к базе, больше на http://makarou.com/mysqli-%E2%80%93-novaya-versiya-rasshireniya-mysql.
Синтаксис этих функций выглядит следующим образом:
mysqli_error($load); mysqli_errno($load);
Как можно заметить, функции принимают только одно значение – это идентификатор соединения с базой данных. Функция mysqli_error – показывает запрос, который завершился ошибкой. А функция mysqli_errno – показывает код ошибки.
Если ошибка возникает в функции подключения к базе данных, то в MySQLi за это отвечают функции mysqli_connect_errno и mysqli_connect_error.
Синтаксис этих функций выглядит вот так:
mysqli_connect_errno(); mysqli_connect_error();
Эти функции не принимают параметров вообще. Функция mysqli_connect_errno – показывает код ошибки. А функция mysqli_connect_error – показывают информацию об ошибке.
Вот небольшой пример как пользоваться этими функциями:
$load=mysqli_connect("localhost","username","pass","dbname", 3306); if(!$load){ echo' Ошибка подключения к БД: '.mysqli_connect_error().' Код ошибки:'.mysqli_connect_errno(); exit; } $sql=mysqli_query("SELECT username FROM accaunt WHERE id='1'"); if(!$sql){ echo'Ошибка запроса: '.mysqli_error($load).' Код ошибки: '.mysqli_errno($load); exit; } $result=mysqli_fetch_array($sql); echo $result['username'];
Вот и все, что нужно знать о выводе ошибок. Ничего тут сложного даже и нет. Я всегда пользуюсь этими функциями при разработке проектов, так как это очень удобно. Сразу понимаешь, что и где случилось. На сегодня все.
Постовой
При ранжировании сайтов, поисковая система Google учитывает один фактор доступности сайта. Скорость отклика сайта зависит от расположения ДНС сервера и хостинг сайта. Можно смело заявить, что платное размещение сайтов, является неотъемлемой частью поисковой оптимизации.
php
(PHP 4, PHP 5)
mysql_error — Возвращает текст ошибки последней операции с MySQL
Описание
mysql_error(resource $link_identifier
= NULL): string
Список параметров
-
link_identifier
-
Соединение MySQL. Если идентификатор соединения не был указан,
используется последнее соединение, открытое mysql_connect(). Если такое соединение не было найдено,
функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров.
Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровняE_WARNING
.
Возвращаемые значения
Возвращает текст ошибки выполнения последней функции MySQL,
или ''
(пустую строку), если операция
выполнена успешно.
Примеры
Пример #1 Пример использования mysql_error()
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "n";mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "n";
?>
Результатом выполнения данного примера
будет что-то подобное:
1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
aleczapka _at) gmx dot net ¶
18 years ago
If you want to display errors like "Access denied...", when mysql_error() returns "" and mysql_errno() returns 0, use $php_errormsg. This Warning will be stored there. You need to have track_errors set to true in your php.ini.
Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says: "Errors coming back from the MySQL database backend no longer issue warnings." Which is not true.
Florian Sidler ¶
12 years ago
Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.
Just spent a good 30 minutes trying to figure out why i didn't see my SQL errors.
Pendragon Castle ¶
14 years ago
Using a manipulation of josh ><>'s function, I created the following. It's purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman's escape_data() as well since I use it in q().
<?phpfunction escape_data($data){
global
$dbc;
if(
ini_get('magic_quotes_gpc')){$data=stripslashes($data);
}
return
mysql_real_escape_string(trim($data),$dbc);
}
function
q($page,$query){// $page$result = mysql_query($query);
if (
mysql_errno()) {$error = "MySQL error ".mysql_errno().": ".mysql_error()."n<br>When executing:<br>n$queryn<br>";$log = mysql_query("INSERT INTO db_errors (error_page,error_text) VALUES ('$page','".escape_data($error)."')");
}
}
// Run the query using q()$query = "INSERT INTO names (first, last) VALUES ('myfirst', 'mylast'");$result = q("Sample Page Title",$query);?>
l dot poot at twing dot nl ¶
16 years ago
When creating large applications it's quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.
This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.
The script writes a log file in directory ( in this case /log ) as well.
The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.
Regars,
Lennart Poot
http://www.twing.nl
<?php
$b_debugmode = 1; // 0 || 1$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';
function
db_query( $query ){
global $b_debugmode;// Perform Query
$result = mysql_query($query);// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
if($b_debugmode){
$message = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
$message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
die($message);
}raise_error('db_query_error: ' . $message);
}
return $result;
}
function
raise_error( $message ){
global $system_operator_mail, $system_from_mail;$serror=
"Env: " . $_SERVER['SERVER_NAME'] . "rn" .
"timestamp: " . Date('m/d/Y H:i:s') . "rn" .
"script: " . $_SERVER['PHP_SELF'] . "rn" .
"error: " . $message ."rnrn";// open a log file and write error
$fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
if($fhandle){
fwrite( $fhandle, $serror );
fclose(( $fhandle ));
}// e-mail error to system operator
if(!$b_debugmode)
mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
}?>
Anonymous ¶
18 years ago
My suggested implementation of mysql_error():
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.n<br />Query: " . $query . "<br />nError: (" . mysql_errno() . ") " . mysql_error());
This will print out something like...
A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong
It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.
Good luck,
-Scott
olaf at amen-online dot de ¶
18 years ago
When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
echo mysql_error ();
?>
Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.
Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?
Anonymous ¶
21 years ago
some error can't handle. Example:
ERROR 1044: Access denied for user: 'ituser@mail.ramon.intranet' to database 'itcom'
This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = "" .
Gianluigi_Zanettini-MegaLab.it ¶
15 years ago
"Errors coming back from the MySQL database backend no longer issue warnings." Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'locallllllhost' (11001)
That's a warning, which is not trapped by mysql_error()!
scott at rocketpack dot net ¶
19 years ago
My suggested implementation of mysql_error():
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.n<br />Query: " . $query . "<br />nError: (" . mysql_errno() . ") " . mysql_error());
This will print out something like...
<b>A fatal MySQL error occured</b>.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong
It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.
Good luck,
-Scott
josh ><> ¶
19 years ago
Oops, the code in my previous post only works for queries that don't return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):
function myquery ($query) {
$result = mysql_query($query);
if (mysql_errno())
echo "MySQL error ".mysql_errno().": ".mysql_error()."n<br>When executing:<br>n$queryn<br>";
return $result;
}
phpnet at robzazueta dot com ¶
16 years ago
This is a big one - As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I'm still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():
MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client
According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:
Set PASSWORD for 'user'@'host' = OLD_PASSWORD('password');
This saved my hide.
miko_il AT yahoo DOT com ¶
19 years ago
Gianluigi_Zanettini-MegaLab.it ¶
15 years ago
A friend of mine proposed a great solution.
<?php
$old_track = ini_set('track_errors', '1');
.....
if (
$this->db_handle!=FALSE && $db_selection_status!=FALSE)
{
$this->connected=1;
ini_set('track_errors', $old_track);
}
else
{
$this->connected=-1;
$mysql_warning=$php_errormsg;
ini_set('track_errors', $old_track);
throw new mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
}
?>
Gerrit ¶
8 years ago
The following code returns two times the same error, even though I would have expected only one:
$ conn = mysql_connect ('localhost', 'root', '');
$ conn2 = mysql_connect ('localhost', 'root', '');
mysql_select_db ('db1', $ conn);
mysql_select_db ('db2', $ conn2);
$ result = mysql_query ("select 1 from dual", $ conn);
$ result2 = mysql_query ("select 1 from luad", $ conn2);
echo mysql_error ($ conn) "<hr>".
echo mysql_error ($ conn2) "<hr>".
The reason for this is that mysql_connect not working as expected a further connection returns. Since the parameters are equal, a further reference to the previous link is returned. So also changes the second mysql_select_db the selected DB of $conn to 'db2'.
If you change the connection parameters of the second connection to 127.0.0.1, a new connection is returned. In addition to the parameters new_link the mysql_connect() function to be forced.
Приветствую всех читателей! Сегодня я хочу вам рассказать про функции вывода ошибок, которые используются в MySQLi. Бывают такие моменты, что запрос к базе завершается ошибкой, и ошибка выводится на экран не в обычном виде. То есть ошибка ссылается просто на строку в файле php, в котором происходит этот запрос к базе. Вот как раз для вывода нормальной информации об ошибках и используются функции MySQLi.
И так приступим.
За предоставление информации об ошибках, в MySQLi используются функции mysqli_errno и mysqli_error. Но эти функции не используются для получения информации об ошибках, возникших в функции соединения с базой данных. То есть эти функции можно использовать только для выявления ошибок, которые возникают в выполнении запросов к базе, больше на http://makarou.com/mysqli-%E2%80%93-novaya-versiya-rasshireniya-mysql.
Синтаксис этих функций выглядит следующим образом:
mysqli_error($load); mysqli_errno($load);
Как можно заметить, функции принимают только одно значение – это идентификатор соединения с базой данных. Функция mysqli_error – показывает запрос, который завершился ошибкой. А функция mysqli_errno – показывает код ошибки.
Если ошибка возникает в функции подключения к базе данных, то в MySQLi за это отвечают функции mysqli_connect_errno и mysqli_connect_error.
Синтаксис этих функций выглядит вот так:
mysqli_connect_errno(); mysqli_connect_error();
Эти функции не принимают параметров вообще. Функция mysqli_connect_errno – показывает код ошибки. А функция mysqli_connect_error – показывают информацию об ошибке.
Вот небольшой пример как пользоваться этими функциями:
$load=mysqli_connect("localhost","username","pass","dbname", 3306); if(!$load){ echo' Ошибка подключения к БД: '.mysqli_connect_error().' Код ошибки:'.mysqli_connect_errno(); exit; } $sql=mysqli_query("SELECT username FROM accaunt WHERE id='1'"); if(!$sql){ echo'Ошибка запроса: '.mysqli_error($load).' Код ошибки: '.mysqli_errno($load); exit; } $result=mysqli_fetch_array($sql); echo $result['username'];
Вот и все, что нужно знать о выводе ошибок. Ничего тут сложного даже и нет. Я всегда пользуюсь этими функциями при разработке проектов, так как это очень удобно. Сразу понимаешь, что и где случилось. На сегодня все.
Постовой
При ранжировании сайтов, поисковая система Google учитывает один фактор доступности сайта. Скорость отклика сайта зависит от расположения ДНС сервера и хостинг сайта. Можно смело заявить, что платное размещение сайтов, является неотъемлемой частью поисковой оптимизации.
php
mysql_error
(PHP 4, PHP 5)
mysql_error — Возвращает текст ошибки последней операции с MySQL
Описание
string mysql_error
([ resource $link_identifier
= NULL
] )
Возвращает текст ошибки выполнения последней функции MySQL.
Ошибки работы с MySQL больше не вызывают сообщений в PHP. Вместо
этого используйте функцию mysql_error(), для
получения сообщения об ошибке. Учтите, что функция возвращает текст
ошибки только последней выполненной функции MySQL (исключая
mysql_error() и mysql_errno()),
поэтому убедитесь, что вы вызываете данную функцию до вызова
следующей функции MySQL.
Список параметров
-
link_identifier -
Соединение MySQL. Если идентификатор соединения не был указан,
используется последнее соединение, открытое mysql_connect(). Если такое соединение не было найдено,
функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров.
Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровняE_WARNING
.
Возвращаемые значения
Возвращает текст ошибки выполнения последней функции MySQL,
или » (пустую строку), если операция
выполнена успешно.
Примеры
Пример #1 Пример использования mysql_error()
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "n";mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "n";
?>
Результатом выполнения данного примера
будет что-то подобное:
1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
Вернуться к: MySQL
Really, it drive me crazy when I can’t detect what error that happens. I can’t handle it.
I managed to make a connection to MySQL, and check it out with:
$connection = mysqli_connect(HOST, USER, PASS, DB) or die('Could not connect!');
if($connection){
echo 'It's connected!';
}
Yeah, that say connected. Then, when I try a query, it fails without error reporting. I’ve tried do this to check if it fails:
$query = "SELECT $field FROM users WHERE id = ".$_SESSION['user_id'];
$result = mysqli_query($dbc, $query);
if($result){
echo 'Query OK';
}else{
echo 'Query failed';
}
The browser said: Query failed. So, there’s an error in my query. Then I echoed the query out with this:
echo $query;
// Printed in the browser: SELECT firstname FROM users WHERE id = 1
Copy that value and use it in phpMyAdmin. It works. So, i guess an error occured in mysqli_query
function. But i can’t get the error message and so i don’t know what’s going on. I’ve tried this:
$result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
and this:
if(!$result){
echo mysqli_error($dbc);
}
Nothing happens. The browser just blank. Then, I tried to change this:
$result = mysqli_query($dbc, $query);
to this:
$result = mysqli_query($query);
Still nothing happens. What’s going on? How can I know what error occured?
I run the server in Debian with phpinfo()
: PHP Version 5.4.36-0+deb7u3
Правильная обработка ошибок позволяет сделать стабильное приложение, которое не будет завершаться неожиданно. В случае возникновения непредвиденной ситуации программа должна выдавать вменяемый ответ, почему она не хочет исполнится. И создание правильного механизма обработки ошибок — это задача программиста.
В этой статье рассмотрим два вида ошибок, которые могут возникнуть при программировании взаимодействия с базой данных. Первый тип — это ошибка подключения к базе данных. Второй тип — это ошибка выполнения запроса к базе данных. Для обработки этих ошибок будем использовать специальные функции для работы с базой.
Ошибка соединения с базой данных
Сразу приведём пример обработки ошибки с соединением с базой данных:
<?php
$host = 'localhost'; // адрес сервера
$db_name = 'database'; // имя базы данных
$user = 'user'; // имя пользователя
$password = 'password'; // пароль
// создание подключения к базе
$connection = mysqli_connect($host, $user, $password, $db_name);
// проверка правильности подключения
if(!$connection){ // при соединении с базой данных возникла ошибка
echo 'Ошибка соединения: ' . mysqli_connect_error() . '<br>';
echo 'Код ошибки: ' . mysqli_connect_errno();
}else{ // соединение было установлено успешно
// здесь можно делать запрос к базе,
// потому что соединение успешно установлено
}
?>
В этом примере можно заметить функцию mysqli_connect_error. Она выводит текстовое описание ошибки подключения (на английском языке). В отличии от неё функция mysqli_connect_errno выводит числовой код ошибки, к примеру «1045».
Ошибка запроса к базе
Теперь попробуем доработать пример из предыдущего параграфа и добавить запрос к базе данных. Не будем вдаваться в детали, что будет записано в тексте SQL запроса, просто предположим, что он может завершиться ошибкой. К примеру, из-за неожиданного отключения сервера с базой данных от сети. В примере добавим проверку на наличие ошибок при выполнении запроса:
<?php
$host = 'localhost'; // адрес сервера
$db_name = 'database'; // имя базы данных
$user = 'user'; // имя пользователя
$password = 'password'; // пароль
// создание подключения к базе
$connection = mysqli_connect($host, $user, $password, $db_name);
if(!$connection){ // проверка правильности подключения
echo 'Ошибка соединения: ' . mysqli_connect_error() . '<br>';
echo 'Код ошибки: ' . mysqli_connect_errno();
}else{ // подключение успешно установлено
// текст SQL запроса, который будет передан базе
$query = 'SELECT * FROM `USERS`';
// выполняем запрос к базе данных
$result = mysqli_query($connection, $query);
if(!$result){ // запрос завершился ошибкой
echo 'Ошибка запроса: ' . mysqli_error($connection) . '<br>';
echo 'Код ошибки: ' . mysqli_errno($connection);
}else{ // запрос успешно выполнился
while($row = $result->fetch_assoc()){
// обрабатываем полученные данные
}
}
// закрываем соединение с базой
mysqli_close($connection);
}
?>
В этом примере есть две функции, которые работают с ошибками базы. Функция mysqli_error возвращает описание ошибки запроса (на английском языке), а функция mysqli_errno возвращает числовой код ошибки, к примеру, «1193».
Обратите внимание, что все функции обработки ошибок в этой статье (mysqli_connect_error, mysqli_connect_errno, mysqli_error, mysqli_errno) возвращают информацию только о последней ошибке. Но ошибок может быть несколько.
Была ли эта статья полезна?
Есть вопрос?
Закажите недорогой хостинг
Заказать
всего от 290 руб
Summary: in this tutorial, you will learn how to use the MySQL SHOW ERRORS
statement to display error information generated by a query.
Introduction to MySQL SHOW ERRORS
statement
The SHOW ERRORS
is a diagnostic statement that displays information for errors.
The SHOW ERRORS
is similar to the SHOW WARNINGS
except that it shows only errors, not warnings and notes.
The following SHOW ERRORS
displays all errors:
Code language: SQL (Structured Query Language) (sql)
SHOW ERRORS;
To limit the number of errors to return, you use the SHOW ERRORS LIMIT
statement:
Code language: SQL (Structured Query Language) (sql)
SHOW ERRORS [LIMIT [offset,] row_count];
The LIMIT
clause has the same meaning as for the SELECT
statement.
To get the total number of errors, you use the following form of the SHOW ERRORS
statement:
Code language: SQL (Structured Query Language) (sql)
SHOW COUNT(*) ERRORS;
Or you can select it from the system variable @@error_count
:
Code language: SQL (Structured Query Language) (sql)
SELECT @@error_count;
MySQL SHOW ERRORS
statement example
This statement returns id from the products
table in the sample database:
Code language: SQL (Structured Query Language) (sql)
SELECT id FROM products;
However, the products
table does not have the id
column.
To show the error, you use the SHOW ERRORS
statement:
Code language: SQL (Structured Query Language) (sql)
SHOW ERRORS;
To get the total number of errors, you use the error_count
variable:
Code language: SQL (Structured Query Language) (sql)
SELECT @@error_count;
In this tutorial, you will have learned how to use the MySQL SHOW ERRORS
statement to display error information.
Was this tutorial helpful?
- PHP
MySQLi
Error Functions - Conclusion
MySQLi
is a PHP function used to access the MySQL database server. You can use this extension if you have MySQL version 4.1.13 or above.
There are various MySQLi
functions that you can use to perform different functions in PHP. In this article, we will learn MySQLi
error functions.
We will also see how and where to use code examples and observe the outputs. For this tutorial, we will use MySQL version 8.0.27 and PHP version 7.4.1.
PHP MySQLi
Error Functions
In this tutorial, we will learn about the following PHP MySQLi
error functions:
mysqli_error()
mysqli_errno()
mysqli_error_list()
mysqli_connect_error()
mysqli_connect_errno()
All these functions can be used in object-oriented style and procedural style. Let’s understand both syntax using the mysqli_error()
function.
Syntax of mysqli_error()
Function in Object Oriented Style
Syntax of mysqli_error()
Function in Procedural Style
string mysqli_error ( mysqli $link )
mysqli_error()
Function in MySQL
This function is used to output the last error description for the most recent function call (if there is any). It is used when you want to know whether the SQL
query has an error or not.
mysqli_error()
returns the error description and empty string if there is no error. See the following example.
Example Code Using Procedural Style:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed");
$sql = "SELECT * FROM teacher";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_error($connection);
if($error_message == ""){
echo "No error related to SQL query.";
}else{
echo "Query Failed: ".$error_message;
}
mysqli_close($connection);
?>
The code given above tries to make the connection using $host
, $username
, $password
, $database
variables and save this connection into the $connection
variable.
mysqli_error()
function will take this connection variable $connection
as a parameter and check if there is any error caused by the recent MySQLi
function call which is mysqli_query($connection, $sql)
here.
Output:
Now, change the table name in the SQL
query from teacher
to person
and observe the output given below.
Output:
We, as a developer, can easily understand that there is no person
table in the person
database (this is what it means in the above error).
Keep the table name changed and replace the line $error_message = mysqli_error($connection);
with $error_message = $connection->error;
to practice and understand the object oriented style using MySQLi
error function.
mysqli_errno()
Function in MySQL
mysqli_errno()
works the same as mysqli_error()
does, but it will return the error code instead of the error description.
Write the following code to practice and understand. You may have noticed that we use a procedural style to practice this function.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed");
$sql = "SELECT * FROM person";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_errno($connection);
if($error_message == ""){
echo "No error related to SQL query.";
}else{
echo "Query Failed: ".$error_message;
}
mysqli_close($connection);
?>
The code given above will show the following output where you will see a number as an error code.
Output:
The question is, why do we use this function to show the numbers only? Because if you want to print a user-friendly error message (custom message), you can use this error code in if-else
statements.
See the following code and its output below.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed");
$sql = "SELECT * FROM person";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_errno($connection);
if($error_message == 1146){
echo "You are trying to read the data from a table which doesn't exist in your database "."'".$database."'";
}
mysqli_close($connection);
?>
Output:
mysqli_error_list()
Function in MySQL
This function is very useful for knowing the error code, SQL state, and error description because this function returns an array containing all the necessary information.
Example Code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed");
$sql = "SELECT * FROM person";
$result = mysqli_query($connection, $sql);
print_r(mysqli_error_list($connection));
mysqli_close($connection);
?>
Output:
mysqli_connect_error()
Function in MySQL
mysqli_connect_error()
returns the error description from the last connection if there is any. Although, the die()
function also tell about the unsuccessful connection but mysqli_connect_error()
returns the error that we can understand easily.
Write the following code first, see its output, and then we’ll compare it with the output produced by mysqli_connect_error()
.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed");
$sql = "SELECT * FROM person";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_error($connection);
if($error_message != ""){
echo "Query Failed: ".$error_message;
}
mysqli_close($connection);
?>
Output:
See the output given above; you can see that the error we can understand is somewhere in the middle.
Imagine, if you have 2 or 3 errors, it would not be easy to find out. Now, use the mysqli_connect_error()
and see the difference using the following code and output.
<?php
$host = "localhost";
$username = "newroot";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed: ".mysqli_connect_error());
$sql = "SELECT * FROM teacher";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_error($connection);
if($error_message != ""){
echo "SQL Query Failed: ".$error_message;
}
mysqli_close($connection);
?>
Output:
The above output clearly says that there is no user named newroot
, which does not allow you to access the database.
mysqli_connect_errno()
Function in MySQL
This function behaves like mysqli_connect_error()
but displays the error code rather than the error message. We can use this error code to write custom error messages.
Example Code:
<?php
$host = "localhost";
$username = "newroot";
$password = "";
$database = "person";
$connection = mysqli_connect($host, $username, $password, $database)
or die("Connection Failed: ".mysqli_connect_errno());
$sql = "SELECT * FROM teacher";
$result = mysqli_query($connection, $sql);
$error_message = mysqli_error($connection);
if($error_message != ""){
echo "SQL Query Failed: ".$error_message;
}
mysqli_close($connection);
?>
Output:
Conclusion
Considering all the discussion and examples, we have concluded two main categories. The first category shows the errors about SQL queries and the other about database connections.
Depending on the project needs, we can print the error message or the error code in each category.
We can display error message in case of an error generated by MySQL query. This meaning full error message gives idea one the problem or bugs in the script. We can print the error message by using mysql function mysql_error(). This function returns the error message associated with most recently executed query. So it is a good idea to check for error before going to next query. We can even add the error number returned by mysql to this error message. This way we can generate a meaningful detail on the bugs on the script.
$querry = mysql_query("SELECT new_field FROM student");
echo "Error message = ".mysql_error();
In our student table there is no field as new_field. Here here is the message we will get
Error message = Unknown column 'new_field' in 'field list'
Note that mysql_error() is deprecated as of PHP 5.5.0 so better to avoid using this function. So if you are using PDO then we can use errorInfo() to display the returned error message from MySQL
Here is a sample code in PHP using PDO to display record and on failure to display error message.
require 'config-pdo.php'; // database connection string
$pdo=$dbo->prepare('Select no_name from student');
if($pdo->execute()){
echo 'Success<br>';
$row = $pdo->fetch(PDO::FETCH_OBJ);
echo "Name : $row->name ";
}else{
print_r($pdo->errorInfo());
}
In the above code there is an error in sql , there is no column by name no_name. The output will be
Array ( [0] => 42S22 [1] => 1054 [2] => Unknown column 'no_name' in 'field list' )
So to get correct result change the sql part like this .
$pdo=$dbo->prepare('Select * from student');
With this you will get desired output.
Handling PDO errors
If such error occurs what is to be done ? We have three options to handle in case of errors.
We can stop the execution of the script. ( Fatal error : stop execution of code )
We can display warning message ( Warning only, display message and no stoppage of execution )
Remain silent ( continue to execute and display error message if required )
Setting the PDO error handling attribute.
We can use setAttribute to tell how to handle the PDO errors.
Here is a sample
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // gives warning only
Here is the complete code.
require 'config-pdo.php'; // database connection string
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // generates fatal error
//$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // gives warning only
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // remain silent
$pdo=$dbo->prepare('Select no_name from student');
if($pdo->execute()){
echo 'Success<br>';
$row = $pdo->fetch(PDO::FETCH_OBJ);
echo "Name : $row->name ";
}else{
print_r($pdo->errorInfo());
}
Now we have given all the three options but commented two and set the attribute to Silent. You can change the commented status and see how the script is behaving in different setAttribute values.
It is clear that the above code will generate error message. We can store the error message in a database or we can post ( by mail ) to the programmer about these details.
Store the error message generated in an sql query or send email >>