Php отладка sql запроса

mysqli_debug

Выполняет процедуры отладки, используя библиотеку Fred Fish.

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

Строка, содержащая выполняемую процедуру отладки

Строка управления отладкой представляет собой последовательность полей, разделённых двоеточиями, как показано ниже:

. Каждое поле состоит из обязательного символа флага, за которым следует необязательный символ , и список модификаторов, разделённый запятыми: flag[,modifier,modifier. modifier]

Допустимые символы флагов

Символ option Описание
O MYSQLND_DEBUG_FLUSH
A/a MYSQLND_DEBUG_APPEND
F MYSQLND_DEBUG_DUMP_FILE
i MYSQLND_DEBUG_DUMP_PID
L MYSQLND_DEBUG_DUMP_LINE
m MYSQLND_DEBUG_TRACE_MEMORY_CALLS
n MYSQLND_DEBUG_DUMP_LEVEL
o вывод в файл
T MYSQLND_DEBUG_DUMP_TIME
t MYSQLND_DEBUG_DUMP_TRACE
x MYSQLND_DEBUG_PROFILE_CALLS

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

Функция всегда возвращает true .

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

Версия Описание
8.0.0 Функция теперь возвращает значение true . Ранее она возвращала значение false в случае возникновения ошибки.

Примеры

Пример #1 Генерация файла трассировки

/* Создать файл трассировки в ‘/tmp/client.trace’ на локальной машине (клиенте): */
mysqli_debug ( «d:t:o,/tmp/client.trace» );

Примечания

Замечание:

Чтобы использовать функцию mysqli_debug() вам нужно скомпилировать клиентскую библиотеку MySQL с поддержкой отладки.

Смотрите также

User Contributed Notes 3 notes

can there be more documenation with a small (but working) example script on how to use this ?

Some issues (Ive seen the «same» code example in dozens of tutorials):-

( I’ll use capitals for emphasis only)

QUESTION: what does D:T:O mean ? UNEXPLAINED.

QUESTION: Do we *ONLY* use these 3 lines in a self-contained script ? Does this log ALL future MYSQL commands ?

QUESTION :- Do we put that one line just

— immediately after we connect to MYSQL ?
— before we connect to MYSQL ?
— before our suspected error ?

Читайте также:  Javascript replace with callback

Here are the information about debug options on mysqli_debug()

O,o:MYSQLND_DEBUG_FLUSH
A,a:MYSQLND_DEBUG_APPEND
F:MYSQLND_DEBUG_DUMP_FILE
L:MYSQLND_DEBUG_DUMP_LINE
m:MYSQLND_DEBUG_TRACE_MEMORY_CALLS
n:MYSQLND_DEBUG_DUMP_LEVEL
o:output to file
T:MYSQLND_DEBUG_DUMP_TIME
t:MYSQLND_DEBUG_DUMP_TRACE
x:MYSQLND_DEBUG_PROFILE_CALLS
f:? still investigating

For example, mysqli_debug(«T:n:t:m:x:F:L:o,/tmp/client.trace»);
mysqlnd will write Time, Level, trace, memory calls, profile calls, File, Line to client.trace file.

22:35:42.704501 ../mysqlnd_connection.c: 269 0:>mysqlnd_connection_init
22:35:42.704538 ../mysqlnd_driver.c: 10 1:| >mysqlnd_driver::get_connection
22:35:42.704549 ../mysqlnd_driver.c: 10 2:| | info : persistent=1
22:35:42.704558 ../mysqlnd_alloc.c: 21 2:| | >_mysqlnd_pecalloc
22:35:42.704570 ../mysqlnd_alloc.c: 23 2:| | 22:35:42.704602 ../mysqlnd_alloc.c: 21 2:| | >_mysqlnd_pecalloc
22:35:42.704626 ../mysqlnd_alloc.c: 23 2:| | 22:35:42.704650 ../mysqlnd_connection.c: 15 2:| | >mysqlnd_error_info_init
22:35:42.704675 ../mysqlnd_connection.c: 10 3:| | | >mysqlnd_error_info::reset
22:35:42.704697 ../mysqlnd_connection.c: 10 3:| | | 22:35:42.704725 ../mysqlnd_connection.c: 16 2:| | 22:35:42.704744 ../mysqlnd_connection.c: 21 2:| | >mysqlnd_connection_state_init

If there is anything wrong, please let me know.

Источник

Common debugging for PHP and MySQL

I see many questions on StackOverflow about database issues. This post aims to provide a checklist to help diagnose common issues. While this post contains PHP and MySQL code samples, this debugging checklist applies to other database platforms.

First, debugging is hard. Especially debugging database issues. Often times the best approach is to systematically rule out what cannot be the problem. This checklist adopts such an approach from a low to high level.

Can you connect to the database outside your application?

Verify you can connect to your database by logging into MySQL from the command line.

 
mysql -u dbuser -p -h localhost database

If you have a specific database user for your application, be sure to verify their credentials as well.

If you do not have command line access, you can use another database administration tool (e.g. PHPMyAdmin).

If you cannot connect to the database, you need to start at the beginning: Ensure MySQL is running, your database exists, and your credentials are correct.

Читайте также:  How to use ttf in css

Can you connect to the database inside your application?

Verify you can connect to the database from PHP. Test with a separate script to also rule out bugs in your codebase:

 
1$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
2
3if (!$link)
4 die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
5>
6
7echo 'Connected. ' . mysqli_get_host_info($link) . "\n";

If this code connects, but your application code does not, debug your application code.

If this code does not connect use the output for clues. You can also check your PHP error logs. It’s likely your MySQL module is misconfigured. Use phpinfo() to review your MySQL configuration.

Does your query run successfully?

More often than not the query is the problem. Especially if the query is generated dynamically. The best way to verify your query it to output and run it yourself.

 
1$sql = 'SELECT column FROM table WHERE column = $bad_var';
2echo $sql;
3if (!$mysqli->query($sql))
4 echo 'Error: ', $mysqli->error;
5>

In this case, we’d see that $bad_var is not set. As such, the query becomes:

 
SELECT column FROM table WHERE column =

Note: This code above is a contrived example of a dynamic query. If you do not see what else is wrong with this query, please read about SQL injection.

You can debug in any order. Top down or bottom up. Just remember this is by no means exhaustive. Nonetheless, following this debugging checklist will help diagnose a majority of your database issues. Please share other common database debugging you use.

Find this interesting? Let’s continue the conversation on Twitter.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A function to help when debugging SQL queries made within PHP

License

craigvantonder/php-debug-sql-query

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A function to help when debugging SQL queries made within PHP .

Example Usage:

// Create a database connection for PHP to use $link = mysqli_connect($DBHost, $DBUser, $DBPass); // Check that the connection is active if (!$link) < dieSql($link); >// Sets encoding type to uft8 if (!mysqli_set_charset($link, 'utf8')) < dieSql($link); >// Set database that is in use if (!mysqli_select_db($link, $DBName))

Another example:

// Build a query $query = 'SELECT `name` '; $query .= 'FROM `people` '; // And run the query if (!$stmt = $link->prepare($query)) < dieSql($link); >if (!$stmt) < dieSql($link); >if (!$stmt->execute()) < dieSql($link); >if (!$stmt->bind_result($name)) < dieSql($link); >$stmt->fetch(); $stmt->close(); 

Debug output:

MySQL Error

Executing Script: /var/www/example.com/public_html/script/SomeClass.php

On Line: 70

MySQL Error Number: 1054

MySQL Error Information: Unknown column ‘name’ in ‘field list’

About

A function to help when debugging SQL queries made within PHP

Источник

Оцените статью