Php mysql report error

mysqli_driver::$report_mode

В зависимости от флагов он устанавливает режим сообщения об ошибках mysqli на исключение, предупреждение или отсутствие. Если установлено значение MYSQLI_REPORT_ALL или MYSQLI_REPORT_INDEX , он также будет информировать о запросах, которые не используют индекс (или используют плохой индекс).

Начиная с PHP 8.1.0, значение по умолчанию — MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT . Раньше это было MYSQLI_REPORT_OFF .

Parameters

Supported flags
Name Description
MYSQLI_REPORT_OFF Отключает отчет
MYSQLI_REPORT_ERROR Сообщать об ошибках при вызове функции mysqli
MYSQLI_REPORT_STRICT Throw mysqli_sql_exception ошибок вместо предупреждений
MYSQLI_REPORT_INDEX Сообщить,если в запросе не использовался индекс или плохой индекс.
MYSQLI_REPORT_ALL Установите все опции (все отчеты)

Return Values

Returns true .

Changelog

Version Description
8.1.0 Значение по умолчанию теперь MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT . Раньше это было MYSQLI_REPORT_OFF .

Examples

Пример # 1 Объектно-ориентированный стиль

 /* activate reporting */ $driver = new mysqli_driver(); $driver->report_mode = MYSQLI_REPORT_ALL; try < /* if the connection fails, a mysqli_sql_exception will be thrown */ $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); /* this query should report an error */ $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000"); /* this query should report a bad index if the column population doesn't have an index */ $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"); > catch (mysqli_sql_exception $e) < error_log($e->__toString()); >

Пример # 2 Процедурный стиль

 /* activate reporting */ mysqli_report(MYSQLI_REPORT_ALL); try < /* if the connection fails, a mysqli_sql_exception will be thrown */ $link = mysqli_connect("localhost", "my_user", "my_password", "my_db"); /* this query should report an error */ $result = mysqli_query($link, "SELECT Name FROM Nonexistingtable WHERE population > 50000"); /* this query should report a bad index if the column population doesn't have an index */ $result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000"); > catch (mysqli_sql_exception $e) < error_log($e->__toString()); >

Пример # 3 Отчет об ошибках, кроме неверных ошибок индекса

 /* activate reporting */ mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try < /* if the connection fails, a mysqli_sql_exception will be thrown */ $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); /* this query should report an error */ $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000"); /* this WILL NOT report any errors even if index is not available */ $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"); > catch (mysqli_sql_exception $e) < error_log($e->__toString()); >

See Also

  • mysqli_sql_exception
  • set_exception_handler () — Устанавливает определяемую пользователем функцию обработчика исключений
  • error_reporting () — Устанавливает, о каких ошибках PHP сообщается
PHP 8.2

(PHP 5 5.1.0,7 7.4.0)mysqli_driver::embedded_server_end mysqli_embedded_server_end Stop Эта функция была УДАЛЕНА в PHP 7.4.0.

(PHP 5 5.1.0,7 7.4.0)mysqli_driver::embedded_server_start mysqli_embedded_server_start Инициализация и Эта функция была УДАЛЕНА в PHP 7.4.0.

(PHP 5,7,8)mysqli_result::$current_field mysqli_field_tell Получение смещения указателя Объектно-ориентированный стиль Процедурный стиль Возвращает позицию поля

Источник

How to report errors in mysqli

Add the following line before mysqli_connect() (or new mysqli() ):

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

Introduction

Reporting errors is the most essential thing in programming. A programmer is effectively deaf-blind if they cannot see errors occurred during the script execution. So it is very important to configure error reporting for your code properly, including database interactions.

By default, when you are running mysqli_query() or — preferably — prepare()/bind()/execute() , mysqli will just silently return false if a query fails, telling you nothing of the reason.

You’ll notice the error only when the following command, when trying to use the query result, will raise an error, such as

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.

Unfortunately, this error message tells you nothing of the actual problem. It just bluntly says that your query failed, and nothing else.

It happens because by default mysqli is configured to remain silent if a query returned an error. So you can tell that’s an extremely inconvenient behavior.

Luckily, mysqli can be configured to throw a PHP exception in case of a mysql error. It means that a PHP error will be thrown automatically every time a query returns an error, without any effort on your part!

Let’s see a small demonstration:

 // first of all set PHP error reporting in general
// in order to be sure we will see every error occurred in the script
ini_set('display_errors',1);
error_reporting(E_ALL);

/*** THIS! ***/
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/*** ^^^^^ ***/
$db = $mysqli = new mysqli($host, $user, $pass, $database);

$res = $db->query("apparently not a valid SQL statement");
$res->fetch_assoc();

And run your script again. Whoa! An error appears in a puff of smoke, explaining what was the problem:

Fatal error: Uncaught exception 'mysqli_sql_exception'
with message 'You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'
apparently not valid SQL string' at line 1' in /home/www/test.php:16
Stack trace
:
#0 /home/www/init.php(16): mysqli->query('apparently not . ')
#1 /home/www/test.php(2): include('/home/www/. ')
#2
thrown in /home/www/init.php on line 16

As you can see, this is quite a detailed information, including the erroneous part of the query, and even a stack trace that helps you to find a particular function that called the erroneous query.

So again: just make sure that you always have this magic line before mysqli_connect() in all your scripts:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

What to do with the error message you get?

It should be a knee-jerk reflex to copy and paste the error message in Google search. It will lead you to several Stack Overflow questions related to this particular problem with many answers with solutions.

However, there is another possibility. You can try to actually read the error message you get. Usually, the error message explains it pretty straightforward, what is the error. However, some errors could be cryptic. You have to understand some considerations used in Mysql error messages:

  • in case of a syntax error, the cited query part begins right after the error.
  • it means that, therefore, if the error is at the very end of the query, the cited query part would be an empty string. Most likely it happens when you add a variable directly to the query and this variable happen to be empty (yet another reason to use prepared statements as they will make such errors just impossible to appear.
  • Mysqli tutorial (how to use it properly)
  • How to connect properly using mysqli
  • How to check whether a value exists in a database using mysqli prepared statements
  • Mysqli helper function
  • Why mysqli prepared statemens are so hard to use?
  • Authenticating a user using mysqli and password_verify()
  • How to get the number rows that has been actually changed
  • Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
  • Mysqli examples
  • Mysqli’s features you probably would like to know about
  • How to run INSERT query using Mysqli
  • How to use mysqli properly

Got a question?

I am the only person to hold a gold badge in , and on Stack Overflow and I am eager to show the right way for PHP developers.

Besides, your questions let me make my articles even better, so you are more than welcome to ask any question you have.

SEE ALSO:

  • Top 10 PHP delusions
  • PDO Examples
  • Mysqli Examples
  • Principles of web-programming
  • Mysqli tutorial (how to use it properly)
  • How to connect properly using mysqli
  • How to check whether a value exists in a database using mysqli prepared statements
  • Mysqli helper function
  • Why mysqli prepared statemens are so hard to use?
  • Authenticating a user using mysqli and password_verify()
  • How to get the number rows that has been actually changed
  • Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
  • Mysqli examples
  • Mysqli’s features you probably would like to know about
  • How to run INSERT query using Mysqli
  • How to use mysqli properly

Latest comments:

  • 17.07.23 21:18
    Jim for (The only proper) PDO tutorial:
    Thanks for the reply! I was hoping you would know if what I’m attempting is even possible! :).
    read more
  • 16.07.23 00:35
    Jim for (The only proper) PDO tutorial:
    Hi, I just discovered this site today, so first and foremost, thank you for all your work.
    read more
  • 27.06.23 05:30
    Jeff Weingardt for MVC in simpler terms or the structure of a modern web-application:
    I was just curious what you find the most effective way to learn php and become proficient? so.
    read more
  • 23.06.23 00:57
    Michael for INSERT query using PDO:
    I read your bit on not needing to check the status of execution. I’m curious, if I needed to.
    read more
  • 10.06.23 17:18
    Ian McKinnon for How to create a search filter for mysqli:
    Please tell me how I can convert this into a prepared statement. ‘A’ indicates that the retrieved.
    read more

Add a comment

Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator’s review.

Comments:

Reply:

Hello Daniel! That’s an interesting question. The simplest solution would be to upgrade the PHP version. Starting from 8.0 bind_param is throwing exceptions all right. For the older versions, it depends on what you need the exception for. Normally, there should be no difference: a Warning as in error all the same, it will be reported and the next call to execute will halt the code execution. But if you really need and exception, you can add a simple error handler to your code that would convert all errors to excepions, like

set_error_handler(function ($level, $message, $file = '', $line = 0)
throw new
ErrorException($message, 0, $level, $file, $line);
>);

See more at https://phpdelusions.net/articles/error_reporting Hope some of these suggestions will help. If not, then please let me know.

a bit misleading if all you have to do is call mysqli_error() and mysqli_errno() no need to reconfigure anything.

Reply:

Hello Chris! There are two problems with this mindset. First, the logic is somewhat inverted here: as long as you have to run only one SQL query, there is not much difference. But even with a dozen, not to mention hundreds of SQL queries, this «call mysqli_error() and mysqli_errno()» after every query becomes «a bit misleading». Now compare it with just «reconfiguring» a single line of code. Second, the question is, what you’re going to do with all these mysqli_error() and mysqli_errno() calls. Are you sure you are going to use them properly? And what if some day you will decide to change that behavior? For example, now you want to die() with the error message but eventually you will learn that it’s just gross and it needs to be changed. So, which approach will make it simpler: when you have just a single place where error reporting is configured, or when you have dozens to hundreds places where you need to rewrite the code?

Источник

mysqli_report

В зависимости от флагов, функция устанавливает режим отчёта об ошибках mysqli на исключение, предупреждение или отсутствие. Если установлено значение MYSQLI_REPORT_ALL или MYSQLI_REPORT_INDEX , функция также будет информировать о запросах, которые не используют индекс (или используют неверный индекс).

Начиная с PHP 8.1.0, по умолчанию установлено значение MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT . Ранее оно было MYSQLI_REPORT_OFF .

Список параметров

Поддерживаемые флаги

Имя Описание
MYSQLI_REPORT_OFF Отключить протоколирование
MYSQLI_REPORT_ERROR Заносить в протокол ошибки вызовов функций mysqli
MYSQLI_REPORT_STRICT Вместо сообщений об ошибках выбрасывать исключение mysqli_sql_exception
MYSQLI_REPORT_INDEX Заносить в протокол факты использования в запросах неверного индекса (или когда индекс не используется вообще)
MYSQLI_REPORT_ALL Включить все настройки (заносить в протокол все события)

Возвращаемые значения

Возвращает true .

Список изменений

Версия Описание
8.1.0 Теперь по умолчанию установлено значение MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT . Ранее оно было MYSQLI_REPORT_OFF .

Источник

Читайте также:  Wordpress вызвать свой php
Оцените статью