Пароль к серверу баз данных утерян
В случае утери пароля создайте новый, выполнив следующие команды.
Остановите MySQL командой:
# service mysql stop - ОС Centos 6/Debian/Ubuntu # systemctl stop mariadb - ОС Centos 7
либо
# systemctl stop mysqld
Выполните запуск MySQL без учета прав доступа командой:
# mysqld_safe --skip-grant-tables &
Зайдите пользователем root командой:
# mysql -uroot
Измените пароль:
# use mysql;
# UPDATE user SET Password=PASSWORD("mypassword") WHERE User='root';
# FLUSH PRIVILEGES;
Перезагрузите сервер баз данных с учетом прав доступа командой:
# service mysqld restart - ОС Centos 6/Debian/Ubuntu # systemctl restart mariadb - ОС Centos 7
либо
# systemctl restart mysqld
Выполните вход на MySQL сервер с новым паролем:
# mysql -uroot -p mypassword
Как просмотреть перечень ошибок MySQL сервера?
Для получения списка ошибок сервера баз данных просмотрите его лог-файлы. Для каждой ОС и файловой системы они располагаются в разных местах. Чтобы определить, где находятся лог-файлы MySQL на вашем сервере, подключитесь к серверу через консоль (например, Putty) и выполните команду, которая найдет файл my.cnf:
find / -name ‘my.cnf’
Результатом выполнения этой команды будут пути, по которым находится файл с этим именем.

Откройте любым редактором, например vi, найденный файл и найдите строки, начинающиеся с “log” или “log-error”
vi /etc/my.cnf

Откройте редактором лог-файл по найденному пути и просмотрите ошибки.

Если в файле my.cnf нет строк, указывающих на лог-файлы, это значит, что контроль ошибок (логирование) не включен. Включите эту функцию, добавив в my.cnf строку:
[mysqld] log-error=/var/log/mysql.log где mysql.log – новый файл, куда будут записываться ошибки.
Создайте его и наделите привилегиями командами:
touch /var/log/mysql.log chown mysql:mysql /var/log/mysql* chmod 640 /var/log/mysql*
При необходимости просмотр лог-файла можно запустить в фоновом режиме, чтобы параллельно запускать другие директивы. Для этого выполните команду:
tail –f /var/log/mysql.log &
Возможные ошибки в лог-файле и их решение
В лог-файле или в браузере выдается ошибка:

Сообщение говорит о том, что в одной из баз данных появилась поврежденная таблица, которую можно восстановить. Для этого подключитесь через консоль к серверу и выполните команду проверки всех таблиц на целостность:
mysqlcheck --repair --analyze --optimize --all-databases -u<USER> –p<PASSWORD>
В случае ошибки запустите несколько команд:
mysqlcheck --repair --all-databases -u<USER> –p<PASSWORD> mysqlcheck --analyze --all-databases -u<USER> –p<PASSWORD> mysqlcheck --optimize --all-databases -u<USER> –p<PASSWORD> где <USER> - пользователь базы данных, <PASSWORD> - пароль.
Если вы знаете, какая именно база данных повреждена, выполните команду:
mysqlcheck --repair --analyze --optimize <DB> -u<USER> -p<PASSWORD> где <USER> - пользователь базы данных, <PASSWORD> - пароль, <BD> - имя поврежденной базы.
Возникает ошибка вида:

Сообщение говорит о том, что запрещен доступ для пользователя user_xxx к базе данных или какой-то ее таблице.
Зайдите в ISPmanager, перейдите в раздел «Базы данных» — нажмите кнопку «Управление серверами БД», двойным кликом на имени сервера баз данных откройте его настройки.
Проверьте, что указанные данные в полях «Имя пользователя» и «Пароль» соответствуют тем, которые находятся в настройках сайта для подключения к этой БД.
На сайте возникает ошибка вида «Не удалось подключиться к базе данных»
Варианты сообщения об ошибке в случае неудачи при подключении к базе данных могут быть следующими:

Убедитесь, что сервер баз данных MySQL запущен. Зайдите в ISPmanager а раздел «Настройки» -> «Конфигурация ПО» и проверьте, что в списке возможностей присутствует строка «Сервер СУБД MySQL» и лампочка в этой строке зелёного цвета. Если лампочка выключена, то выделите строку и нажмите «Установить» на панели инструментов.
Если проблема не исчезла, то подключитесь к серверу через консоль и перезапустите MySQL командой:
/etc/init.d/mysqld restart - ОС Centos 6, Debian systemctl restart mysqld - ОС Centos 7
Проверьте, что сервер корректно запустился, выполнив команду, которая выводит список процессов MySQL:
ps axuw | grep mysql
Если в результате не вывелось ни одного процесса, то MySQL не запустился.
Не удается запустить MySQL
Попробуйте запустить MySQL через панель управления ISPmanager. Если не получилось, то подключитесь к серверу по SSH и попробуйте запустить MySQL через консоль командой:
/etc/init.d/mysqld restart - ОС Centos 6, Debian systemctl restart mariadb - ОС Centos 7
Если MySQL не запускается через консоль, вы получите сообщение об ошибке вида:
Проверьте свободное место на диске командой
df -h

Команда
du –hs /*
выведет, сколько места занимает каждая директория.

Если свободного места осталось мало, освободите его, очистив в первую очередь лог-файлы MySQL и других служб.
Перезапустите MySQL через консоль командами, приведенными выше.
Если проблема сохранилась, внимательно изучите записи в лог-файле MySQL, начинающиеся с [ERROR]. Например, запись Error while setting value ‘—read_buffer_size=256K’ to ‘sort_buffer_size’ означает, что директива sort_buffer_size в конфигурационном файле MySQL, прописана не верно.
Журналы событий — первый и самый простой инструмент для определения статуса системы и выявления ошибок. Основных логов в MySQL четыре:
Помогаем

- Error Log — стандартный лог ошибок, которые собираются во время работы сервера (в том числе start и stop);
- Binary Log — лог всех команд изменения БД, нужен для репликации и бэкапов;
- General Query Log — основной лог запросов;
- Slow Query Log — лог медленных запросов.
Приборкайте Power BI і прогнозуйте майбутнє своєї компанії.
РЕЄСТРУЙТЕСЯ!

Лог ошибок
Этот журнал содержит все ошибки, которые произошли во время работы сервера, включая критические ошибки, а также остановки, включения сервера и предупреждения (warnings). С него нужно начать в случае сбоя системы. По умолчанию все ошибки выводятся в консоль (stderr), также можно записывать ошибки в syslog (по умолчанию в Debian) или отдельный лог-файл:
log_error=/var/log/mysql/mysql_error.log
Ошибки будут писаться в mysql_error.log
Рекомендуем держать этот журнал включенным для быстрого определения ошибок. А для понимания, что значит та или иная ошибка, в MySQL присутствует утилита [http://dev.mysql.com/doc/refman/5.7/en/perror.html perror]:
shell> perror 13 64 OS error code 13: Permission denied OS error code 64: Machine is not on the network
Объясняет значения кодов ошибок
Бинарный (он же двоичный) лог
В бинарный лог записываются все команды изменения базы данных, пригодится для репликации и восстановления.
Включается так:
log_bin = /var/log/mysql/mysql-bin.log expire_logs_days = 5 max_binlog_size = 500M
Указывает расположение, срок жизни и максимальный размер файла
Учтите, что если вы не собираетесь масштабировать систему и реализовывать отказоустойчивость, то бинарный лог лучше не включать. Он требователен к ресурсам и снижает производительность системы.
Лог запросов
В этом журнале содержатся все полученные SQL-запросы, информация о подключениях клиентов. Может пригодиться для анализа индексов и оптимизации, а также выявления ошибочных запросов:
general_log_file = /var/log/mysql/mysql.log general_log = 1
Включает лог и указывает расположение файла
Также его можно включить/отключить во время работы сервера MySQL:
SET GLOBAL general_log = 'ON'; SET GLOBAL general_log = 'OFF';
Для применения не нужно перезагружать сервер
Лог медленных запросов
Журнал пригодится для определения медленных, то есть неэффективных запросов. Подробнее читайте в этой статье.
Просмотр логов
Для просмотра логов на Debian (Ubuntu) нужно выполнить:
# Лог ошибок tail -f /var/log/syslog #Лог запросов tail -f /var/log/mysql/mysql.log # Лог медленных запросов tail -f /var/log/mysql/mysql-slow.log
Если логи не указаны отдельно, то находятся в /var/lib/mysql
Ротация логов
Не забывайте сжимать (архивировать, ротировать) файлы логов, чтобы они занимали меньше места на сервере. Для этого используйте утилиту logrotate, отредактировав файл конфигурации /etc/logrotate.d/mysql-server:
# - I put everything in one block and added sharedscripts, so that mysql gets
# flush-logs'd only once.
# Else the binary logs would automatically increase by n times every day.
# - The error log is obsolete, messages go to syslog now.
/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log {
daily
rotate 7
missingok
create 640 mysql adm
compress
sharedscripts
postrotate
test -x /usr/bin/mysqladmin || exit 0
# If this fails, check debian.conf!
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
if [ -z "`$MYADMIN ping 2>/dev/null`" ]; then
# Really no mysqld or rather a missing debian-sys-maint user?
# If this occurs and is not an error please report a bug.
#if ps cax | grep -q mysqld; then
if killall -q -s0 -umysql mysqld; then
exit 1
fi
else
$MYADMIN flush-logs
fi
endscript
}
Сжимает и архивирует нужные логи, очищает файлы
DDL Log
MySQL также ведет лог языка описания данных. В него собираются данные операций типа DROP_TABLE and ALTER_TABLE. Лог используется для восстановления после сбоев, которые произошли во время выполнения таких операций. [http://dev.mysql.com/doc/refman/5.7/en/ddl-log.html DDL Log] — бинарный файл, не предназначенный для чтения пользователем, поэтому не модифицируйте и не удаляйте его.
Самое главное
Всегда включайте лог ошибок, используйте лог запросов для проверки соединения приложения с базой данных, проверки запросов и работы memcached. Лог медленных запросов пригодится для оптимизации работы MySQL.
Этот текст был написан несколько лет назад. С тех пор упомянутые здесь инструменты и софт могли получить обновления. Пожалуйста, проверяйте их актуальность.
26 марта, 2019 12:22 пп
881 views
| Комментариев нет
MariaDB, mySQL
Эта серия статей научит вас устранять неполадки и диагностировать ваш экземпляр MySQL. Мы рассмотрим базовые проблемы, с которыми сталкиваются многие пользователи MySQL, а также предоставим вам инструкции по их устранению. Также вы найдете здесь ссылки на другие полезные статьи и мануалы.
Очень часто главную причину замедления, сбоев или другого непредсказуемого поведения MySQL можно найти, проанализировав лог ошибок. В системах Ubuntu этот файл MySQL по умолчанию расположен в /var/log/mysql/error.log. В большинстве случаев для чтения логов рекомендуется использовать команду less (это утилита командной строки, которая позволяет просматривать файлы, но не редактировать их). Чтобы просмотреть лог ошибок, введите:
sudo less /var/log/mysql/error.log
Если MySQL ведет себя странно, вы можете получить больше информации об источнике проблемы, запустив эту команду. В логе вы найдете информацию, необходимую для диагностики проблем и их устранения.
Читайте также: Устранение неполадок в запросах MySQL
Tags: MySQL
Журналы событий — первый и самый простой инструмент для определения статуса системы и выявления ошибок. Основных логов в MySQL четыре:
- Error Log — стандартный лог ошибок, которые собираются во время работы сервера (в том числе start и stop);
- Binary Log — лог всех команд изменения БД, нужен для репликации и бэкапов;
- General Query Log — основной лог запросов;
- Slow Query Log — лог медленных запросов.
Лог ошибок
Этот журнал содержит все ошибки, которые произошли во время работы сервера, включая критические ошибки, а также остановки, включения сервера и предупреждения (warnings). С него нужно начать в случае сбоя системы. По умолчанию все ошибки выводятся в консоль (stderr), также можно записывать ошибки в syslog (по умолчанию в Debian) или отдельный лог-файл:
|
log_error=/var/log/mysql/mysql_error.log |
Рекомендуем держать этот журнал включенным для быстрого определения ошибок. А для понимания, что значит та или иная ошибка, в MySQL присутствует утилита perror:
|
shell> perror 13 64 OS error code 13: Permission denied OS error code 64: Machine is not on the network |
Бинарный (он же двоичный) лог
В бинарный лог записываются все команды изменения базы данных, пригодится для репликации и восстановления.
Включается так:
|
log_bin = /var/log/mysql/mysql-bin.log expire_logs_days = 5 max_binlog_size = 500M |
Учтите, что если вы не собираетесь масштабировать систему и реализовывать отказоустойчивость, то бинарный лог лучше не включать. Он требователен к ресурсам и снижает производительность системы.
Лог запросов
В этом журнале содержатся все полученные SQL-запросы, информация о подключениях клиентов. Может пригодиться для анализа индексов и оптимизации, а также выявления ошибочных запросов:
|
general_log_file = /var/log/mysql/mysql.log <b>general_log = 1</b> |
Также его можно включить/отключить во время работы сервера MySQL:
|
SET GLOBAL general_log = ‘ON‘; SET GLOBAL general_log = ‘OFF‘; |
Лог медленных запросов
Журнал пригодится для определения медленных, то есть неэффективных запросов. Подробнее читайте в этой статье.
Просмотр логов
Для просмотра логов на Debian (Ubuntu) нужно выполнить:
|
# Лог ошибок tail -f /var/log/syslog <span class=«comment»> #Лог запросов </span>tail -f /var/log/mysql/mysql.log <span class=«comment»> # Лог медленных запросов </span>tail -f /var/log/mysql/mysql-slow.log |
Ротация логов
Не забывайте сжимать (архивировать, ротировать) файлы логов, чтобы они занимали меньше места на сервере. Для этого используйте утилиту logrotate, отредактировав файл конфигурации /etc/logrotate.d/mysql-server:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# — I put everything in one block and added sharedscripts, so that mysql gets <span class=«comment»> # flush-logs’d only once. </span># Else the binary logs would automatically increase by n times every day. <span class=«comment»> # — The error log is obsolete, messages go to syslog now. </span><b>/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log</b> { daily rotate 7 missingok create 640 mysql adm compress sharedscripts postrotate test -x /usr/bin/mysqladmin || exit 0 <span class=«comment»> # If this fails, check debian.conf! </span> MYADMIN=«/usr/bin/mysqladmin —defaults-file=/etc/mysql/debian.cnf» if [ -z «`$MYADMIN ping 2>/dev/null`» ]; then <span class=«comment»> # Really no mysqld or rather a missing debian-sys-maint user? </span> <span class=«comment»> # If this occurs and is not an error please report a bug. </span> <span class=«comment»> #if ps cax | grep -q mysqld; then </span> if killall -q -s0 -umysql mysqld; then exit 1 fi else $MYADMIN flush-logs fi endscript } |
DDL Log
MySQL также ведет лог языка описания данных. В него собираются данные операций типа DROP_TABLE and ALTER_TABLE. Лог используется для восстановления после сбоев, которые произошли во время выполнения таких операций. DDL Log — бинарный файл, не предназначенный для чтения пользователем, поэтому не модифицируйте и не удаляйте его.
Самое главное
Всегда включайте лог ошибок, используйте лог запросов для проверки соединения приложения с базой данных, проверки запросов и работы memcached. Лог медленных запросов пригодится для оптимизации работы MySQL.
https://github.com/midnight47/
I’ve read that Mysql server creates a log file where it keeps a record of all activities — like when and what queries execute.
Can anybody tell me where it exists in my system? How can I read it?
Basically, I need to back up the database with different input [backup between two dates] so I think I need to use log file here, that’s why I want to do it…
I think this log must be secured somehow because sensitive information such as usernames and password may be logged [if any query require this]; so may it be secured, not easily able to be seen?
I have root access to the system, how can I see the log?
When I try to open /var/log/mysql.log it is empty.
This is my config file:
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
log = /var/log/mysql/mysql.log
binlog-do-db=zero
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
general_log_file = /var/log/mysql/mysql.log
general_log = 1
kenorb
149k79 gold badges667 silver badges722 bronze badges
asked Mar 26, 2011 at 11:21
![]()
Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.
-
The Error Log. It contains information about errors that occur while
the server is running (also server start and stop) -
The General Query Log. This is a general record of what mysqld is
doing (connect, disconnect, queries) -
The Slow Query Log. Ιt consists of «slow» SQL statements (as
indicated by its name).
By default no log files are enabled in MYSQL. All errors will be shown in the syslog (/var/log/syslog).
To Enable them just follow below steps:
step1: Go to this file (/etc/mysql/conf.d/mysqld_safe_syslog.cnf) and remove or comment those line.
step2: Go to mysql conf file (/etc/mysql/my.cnf) and add following lines
To enable error log add following
[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
To enable general query log add following
general_log_file = /var/log/mysql/mysql.log
general_log = 1
To enable Slow Query Log add following
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
step3: save the file and restart mysql using following commands
service mysql restart
To enable logs at runtime, login to mysql client (mysql -u root -p) and give:
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
Finally one thing I would like to mention here is I read this from a blog. Thanks. It works for me.
Click here to visit the blog
Nik
2,7252 gold badges23 silver badges25 bronze badges
answered Apr 2, 2015 at 9:52
![]()
loyolaloyola
3,7652 gold badges24 silver badges18 bronze badges
10
The MySQL logs are determined by the global variables such as:
log_errorfor the error message log;general_log_filefor the general query log file (if enabled bygeneral_log);slow_query_log_filefor the slow query log file (if enabled byslow_query_log);
To see the settings and their location, run this shell command:
mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log -e slow_query_log
To print the value of error log, run this command in the terminal:
mysql -e "SELECT @@GLOBAL.log_error"
To read content of the error log file in real time, run:
sudo tail -f $(mysql -Nse "SELECT @@GLOBAL.log_error")
Note: Hit Control—C when finish
When general log is enabled, try:
sudo tail -f $(mysql -Nse "SELECT CONCAT(@@datadir, @@general_log_file)")
To use mysql with the password access, add -p or -pMYPASS parameter. To to keep it remembered, you can configure it in your ~/.my.cnf, e.g.
[client]
user=root
password=root
So it’ll be remembered for the next time.
answered Jun 7, 2016 at 17:09
kenorbkenorb
149k79 gold badges667 silver badges722 bronze badges
2
You have to activate the query logging in mysql.
-
edit /etc/my.cnf
[mysqld] log=/tmp/mysql.log
-
restart the computer or the mysqld service
service mysqld restart
-
open phpmyadmin/any application that uses mysql/mysql console and run a query
-
cat /tmp/mysql.log( you should see the query )
Nik
2,7252 gold badges23 silver badges25 bronze badges
answered Mar 26, 2011 at 11:28
![]()
johnlemonjohnlemon
20.5k40 gold badges118 silver badges178 bronze badges
2
From the MySQL reference manual:
By default, all log files are created in the data directory.
Check /var/lib/mysql folder.
kenorb
149k79 gold badges667 silver badges722 bronze badges
answered Mar 26, 2011 at 11:29
![]()
Mark NenadovMark Nenadov
6,2415 gold badges22 silver badges29 bronze badges
5
In my (I have LAMP installed) /etc/mysql/my.cnf file I found following, commented lines in [mysqld] section:
general_log_file = /var/log/mysql/mysql.log
general_log = 1
I had to open this file as superuser, with terminal:
sudo geany /etc/mysql/my.cnf
(I prefer to use Geany instead of gedit or VI, it doesn’t matter)
I just uncommented them & save the file then restart MySQL with
sudo service MySQL restart
Run several queries, open the above file (/var/log/mysql/mysql.log) and the log was there 🙂
![]()
answered Apr 2, 2014 at 13:04
LineLine
1,4913 gold badges18 silver badges41 bronze badges
1
Enter MySQL/MariaDB server command-line tool as root
- Set file path (you can replace general.log with the file name of your choice).
SET GLOBAL general_log_file=’/var/log/mysql/general.log’;
- Set log file format
SET GLOBAL log_output = ‘FILE’;
- Enable the server general log
SET GLOBAL general_log = ‘ON’;
- Check your configurations in global configuration variables.
SHOW VARIABLES LIKE «general_log%»;

- Enter
exitto leave MySQL command-line and Tail your queries by
tail -f /var/log/mysql/general.log
or
less /var/log/mysql/general.log
- To disable the general server log
SET GLOBAL general_log = ‘OFF’;
answered Jun 7, 2022 at 12:28
To complement loyola’s answer it is worth mentioning that as of MySQL 5.1 log_slow_queries is deprecated and is replaced with slow-query-log
Using log_slow_queries will cause your service mysql restart or service mysql start to fail
answered Sep 9, 2016 at 14:54
![]()
In addition to the answers above you can pass in command line parameters to the mysqld process for logging options instead of manually editing your conf file. For example, to enable general logging and specifiy a file:
mysqld --general-log --general-log-file=/var/log/mysql.general.log
Confirming other answers above, mysqld --help --verbose gives you the values from the conf file (so running with command line options general-log is FALSE); whereas mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log gives:
general_log ON
general_log_file /var/log/mysql.general.log
Use slightly more compact syntax for the error log:
mysqld --general-log --general-log-file=/var/log/mysql.general.log --log-error=/var/log/mysql.error.log
answered Aug 22, 2016 at 11:02
![]()
br3w5br3w5
4,2834 gold badges32 silver badges42 bronze badges
shell> mysqladmin flush-logs
shell> mv host_name.err-old backup-directory
![]()
Shaunak D
20.5k10 gold badges45 silver badges78 bronze badges
answered Apr 15, 2015 at 13:27
1
- Home
- Coding
- MySQL
- Журналы работы сервера MySQL — ошибок, двоичные, общих запросов, медленных запросов
Статья содержит краткое описание журналов работы сервера MySQL — журнал ошибок, общий журнал запросов, журнал медленных запросов, двоичные журналы
Все журналы связанные с работой сервера MySQL по умолчанию находятся в папке data корневой папки MySQL (той паки куда был установлен MySQL).
Представляет файл с расширением .err. В качестве имени файла берется hostname (hostname.err). Содержит информацию об ошибках в работе, запусках и остановках сервера. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.
Общий журнал запросов MySQL
Представляет файл с расширением .log. В качестве имени файла берется hostname (hostname.log). Содержит информацию о подключениях клиентских программ и выполняемых запросах. Для ведения этих журналов сервер должен быть запущен с параметром – log. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.
Журнал медленных запросов MySQL
Представляет файл с именем hostname-show.log. Содержит информацию об длительных АО времени SQL-запросах (по умолчанию – более 10 с), служит для обнаружения объектов, требующих оптимизации. Для ведения этих журналов сервер должен быть запущен с параметром – log-slow-queries. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.
Двоичные журналы MySQL
Представляет файл с именем hostname-bin.xxxxxx, где xxxxxx – порядковый номер журнала. Содержат историю изменений данных в базе. Для ведения этих журналов сервер должен быть запущен с параметром – log-bin. Для просмотра двоичных журналов необходимо использовать специальную утилиту mysqlbinlog (запускается из командной строки)
mysqlbinlog hostname-bin.xxxxxx — Выведет содержимое в виде SQL-команд.
mysqlbinlog hostname-bin.xxxxxx filename – Запишет содержимое в виде SQL-команд в файл, который можно посмотреть любым текстовым редактором.
На этом все, всем пока.
Меня два раза спрашивали [члены Парламента]: «Скажите на милость, мистер Бэббидж, что случится, если вы введёте в машину неверные цифры? Cможем ли мы получить правильный ответ?» Я не могу себе даже представить, какая путаница в голове может привести к подобному вопросу. / Charles Babbage /
(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().
<?php
function 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.