Как найти ошибку в sql запросе

Как найти ошибку в SQL-запросе

SQL-запрос — это то, что либо работает хорошо, либо не работает вообще, частично он никак работать не может, в отличие, например, от того же PHP. Как следствие, найти ошибку в SQL-запросе, просто рассматривая его — трудно, особенно если этот запрос снабжён целой кучей JOIN и UNION. Однако, в этой статье я расскажу о методе поиска ошибок в SQL-запросе.

Поскольку обычно в SQL-запрос подставляются какие-то переменные в PHP, то необходимо его сначала вывести. Сделать это можно, например, так:

<?php
  $a = 5;
  $query = "SELECT FROM `table` WHERE `id` = '$a'";
  $result_set = $mysqli->query($query); // Не работает
  echo $query; // Выводим запрос, который отправляется
?>

В результате, скрипт выведет такой запрос: SELECT FROM `table` WHERE `id` = ‘5’. Теперь чтобы найти ошибку в нём, надо зайти в phpMyAdmin, открыть базу данных, с которой происходит работа, открыть вкладку «SQL» и попытаться выполнить запрос.

И вот здесь уже ошибка будет показана, не в самой понятной форме (иногда прямо точно описывает ошибку), но она будет. Вот что написал phpMyAdmin: «#1064 — 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 ‘FROM `table` WHERE `id` = ‘5’ ORDER BY `table`.`id` ASC LIMIT 0, 30′ at line 1«. Это означает, что ошибка рядом с FROM. Присматриваемся к этому выделенному нами небольшому участку и обнаруживаем, что мы забыли поставить «*«. Исправляем сразу в phpMyAdmin эту ошибку, убеждаемся, что запрос сработал и после этого идём исправлять ошибку уже в коде.

С помощью этого метода я нахожу абсолютно все ошибки в SQL-запросе, которые мне не удаётся обнаружить непосредственно при осмотре в PHP-коде.

Надеюсь, теперь и Вы сможете найти ошибку в любом SQL-запросе.

  • Создано 01.05.2013 10:54:01


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

����� 1. ��������� �������.

����� 1. ������.

�������� ������ �� ��� �����, ���� �� �� ��������� ����� ����������, ��� ����� ������� ������ ����� ���� ������� � ������ �������. ��� �� ��ɣ� ����� ��������� � � ��������� SQL ����������.

��� ������ ��������� ������ � ������� ��������. ������ � ���� ������ ��������� ����� ������.


select * fro t1 where f1 in (1,2,1);

� �����, ����������� ��������� ��� �������� � ޣ� ��������. ���� ��������� ���� ������ � mysql cli ������ ������ �ݣ ��������:


mysql> select * fro t1 where f1 in (1,2,1);
ERROR 1064 (42000): 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 'fro t1 where f1 in (1,2,1)' at line 1

�� ���� ��� �������������� ������: ������� �������� ����� o � ��������� from. ������, �� ������ ��?

����ͣ� ������ ���������. ��� ��� �� PHP. (��� ��������� ��������� �������, ��� ��� ��� ����������� ��� PHP ����������� � ������. ����������� �������� ����� �������� � �� ����� ������ ����� ������� ����� ����������������.)


$query = 'SELECT * FROM t4 WHERE f1 IN(';
for ($i = 1; $i < 101; $i ++)
$query .= "'row$i,";
$query = rtrim($query, ',');
$query .= ')';
$result = mysql_query($query);

� ������ ������ ��������� ������ ��� �������. � ��� ����� � ������ �ݣ ����� �������� �������?

� ������ � PHP ��� ������� ������� ������� echo, ������� ������������ �����:


$query = 'SELECT * FROM t4 WHERE f1 IN(';
for ($i = 1; $i < 101; $i ++)
$query .= "'row$i,";
$query = rtrim($query, ',');
$query .= ')';
echo $query;
//$result = mysql_query($query);

�������� ������:


$php phpconf2009_1.php
SELECT * FROM t4 WHERE f1 IN('row1,'row2,'row3,'row4,'row5,'row6,'row7,'row8,'row9,'row10,'row11,
'row12,'row13,'row14,'row15,'row16,'row17,'row18,'row19,'row20)

� ��� ��� ������ ���������� ����� ���������: �������� ����������� �������� � ���������


$query .= "'row$i,";

���������� �������� ��� ����������


$query .= "'row$i',";

� ������ ����� ����������� �����.

�������� ��������, ��� �� �������� ������ ������ � ��� ����, � ������� ��� �������� ����. ������� ����� ����� ������ � ������� �������, ��� � ������, ������� ���������� �� ������ ������ ��� �������� ����������.

������������� ��������� ������ ��� ��������� ����������� ������� ����������, �� ����������� ��ɣ�.

��ɣ� 1: ����������� �������� ������ ��� ������ ������� � ��� ����, � ������� ��� �������� ����.

� ��������� �� �� ������ ����� ������������ echo. �������� � ������ ��������� ������������� �������� ����������.

��������� �� ��������� ������.

�������� �������� �� web-�������� �� �������� �����������:


��������� �������

    * �������
    * ����
    * test2
    * test2
    * test2
    * test2
    * test2

������� �������� ����� �������:

<>

��������:

<>

<Go!>

�������� � ���, ��� � ��� �����-�� ������� ������������ ��������� ������ � ���������� ������.

��������� �� ���, ������� �� ��� ��������:


$system = System::factory()
->setName($this->form->get(Field::NAME))
->setDescription(
$this->form->get(Field::DESCRIPTION)
);
DAO::system()->take($system);

���-������ �������? � ����� ������� ������� ����� ������������ � ޣ� ��������, �� � ����� ������ ��� ������ ��������, ������� ���������� ����������� ��� ������������. �ݣ ����� ������� ��� � ���� ������� �������� ����� � ����� ���� ������: � ��� ��� �� ��������� � ����, �� �������.

� PHP ���������� ����� �������� ��� ����������, ������� �������� �� ���������� �������, ����� �� ������� ��� (������) � ���� ��� �� stderr ����� ���, ��� ��������� ����, �� � ������ � �������������� �������, ��������, � Java, ���������� ����� �����������������. �� � �� ������ ��� ���������� ������.

��� �� ������? � ������ � MySQL �� ����� ��������� general query log:


mysql> set global log_output='table';
Query OK, 0 rows affected (0.00 sec)


mysql> select * from mysql.general_log;
Empty set (0.09 sec)


mysql> set global general_log='on';
Query OK, 0 rows affected (0.00 sec)

��������� ����������.


mysql> select * from mysql.general_log order by event_time desc limit 25G
*************************** 1. row ***************************
  event_time: 2009-10-19 13:00:00
   user_host: root[root] @ localhost []
   thread_id: 10323
   server_id: 60
command_type: Query
    argument: select * from mysql.general_log order by event_time desc limit 25
...
*************************** 22. row ***************************
  event_time: 2009-10-19 12:58:20
   user_host: root[root] @ localhost [127.0.0.1]
   thread_id: 10332
   server_id: 60
command_type: Query
    argument: INSERT INTO `system` (`id`, `name`, `description`) VALUES ('', 'test2', '')
...
mysql> set global general_log='off';
Query OK, 0 rows affected (0.08 sec)

� 22 ������ �� ����� ��� ������. �� �� �������� ����������: ������� INSERT.

��������� ��� �� ����� � ������� system:


mysql> select * from system;
+----+---------+------------------------------------------+
| id | name    | description                              |
+----+---------+------------------------------------------+
|  1 | �������  | ��������������� ������� � ������� ������      |
|  2 | ����     | �������� �������������� �����                 |
|  3 | test2   | New test                                 |
|  4 | test2   | foobar                                   |
|  8 | test2   |                                          |
+----+---------+------------------------------------------+
5 rows in set (0.00 sec)

��������� ţ �����������:


mysql> show create table systemG
*************************** 1. row ***************************
       Table: system
Create Table: CREATE TABLE `system` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `description` tinytext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
1 row in set (0.09 sec)

���� name �� �������� ����������. ������� �� ����� ������ �������� � ����������� ����� ���������: ����� ���� ������� ��� ���� ����������


(alter table system add unique(name))

���� �������� ���������� ����� �������, ����� ��� �������� �������������� �� �� ������ SQL.

�� ������ ��� ����������� ��������� ��ɣ�: ����������� general query log ��� ��������� �������, ������� �������� ������������ ���������.

��ɣ� 2: ����������� general query log, ���� ��� ����� ���������� ����� ������ ������ �������� ������������ ��������� ������ ����������.

�� ���������, ��� ����������� ������ ����� �������� ������, ��������� �������� � ����������. � ����������� ������� ����� ����������, ����� ����� � ��������� ������. ��� ���������, ������ ������� ����� ������� ������ � ������ ������ ��� ������ ����������� �������. �������, ���������� ��������, ����� ����������� ���������� ������� �� ����������. ��� �������� ����� ����������� ��������.
� ������ �� �������� ���� �������� �� ��������� �������:


mysql> select * from mysql.general_log;
Empty set (0.09 sec)


mysql> set global general_log='on';
Query OK, 0 rows affected (0.00 sec)

...

mysql> set global general_log='off';
Query OK, 0 rows affected (0.08 sec)

����� ��� ����� �������� �������� ���������� ����������, ���� �� ����� �������� general query log � ���������������� �����?

���� � ���, ��� general query log ��� �� ���� ������ �����������: �� ����������� �������� �� ������ � ��� ��� �� �������� ��� �������, �� ��� ����� ����� ������� �� ������ �� �����. ������� �� � ������ 5.1 ��� ����� ��������-��������� � ������ ��������� ������� ��� ����� ����� �������������� �������� �� MySQL ������ � ��������.

��������� ������ �������� ����� �� � ����, � � �������. ����� � ������� ����� ��� ��������� ����� ���������� �������� ��� � ��������� 2-�� ��������, ��� ��� ������� ����� �������������: �� ����������� � ��� ����� ��� � ����� ������ �������.


mysql> set global log_output='table';
Query OK, 0 rows affected (0.00 sec)

Время на прочтение
1 мин

Количество просмотров 1.1K

По мотивам своего мастер-класса на PHPConf 2009 (http://phpconf.ru) я написала гид для тех, кому нужно поймать ошибку в SQL приложении. Правильнее было бы назвать в MySQL приложении, но я всё-таки думаю, что общие принципы едины для всех. В идеале мне бы хотелось, чтобы текст охватывал основные случаи неправильного поведения. Оговорюсь, что под неправильным поведением я понимаю логические ошибки, а не проблемы производительности. Проблемы производительности — это отдельная тема, кстати, достаточно хорошо представленная в сети.

Книжка состоит из 4 частей, ниже можно посмотреть краткое содержание:

Часть 1. Одиночные запросы.
Рассмотрены случаи, когда ошибка повторяется для одного клиента-потока.

Часть 2. Конкурентные запросы.
Случаи, когда ошибка повторяется только в случаях, когда несколько клиентов работают с базой одновременно.

Часть 3. Другие случаи.
Случаи, не подходящие под предыдущие определения.

Часть 4. Техники, применяющиеся для отладки Production приложений.
Краткий перечень того, что нужно делать, если приходится тестировать на рабочем сервере.

Текст получился достаточно объёмный, поэтому я посчитала нужным дать ссылку на внешний ресурс, а не выкладывать здесь, так как получилось достаточно «много букаф», а несколько постов подряд на одну тему может утомить.

Пожалуйста, почитайте и покритикуйте. Ваше мнение очень интересно. Комментарии оставляйте здесь :)

Почитать можно здесь: sql-error.microbecal.com

After searching for a CLI tool for syntax linting in Mysql to use in Jenkins and didn’t find anything quickly (this Stackoverflow question is one of the first results — LOL) I came up with the following solution (OS: Linux, but should be feasible with Windows too):

Something like the follwoing:

lint_result=`mysql mysql_test -B -f -e 'select asdf s where x;' 2>&1`; if [ `echo $lint_result | sed -r "s/ERROR ([0-9]*).*/1/g"` -eq 1064 ]; then echo -e "Syntax error:n${lint_result}"; fi
Syntax error:
ERROR 1064 (42000) at line 1: 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 'where x' at line 1

(To check sql files you can use «< filename.sql» instead of -b -e ‘statement’)

If the syntax of the query can not be parsed by mysql it claims:
ERROR 1064 (42000) at line 1: 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 » at line 1

Only if the syntax is correct it tries to execute the query and realize that the table don’t exists but this isn’t interesting anymore:

ERROR 1146 (42S02) at line 1: Table 'mysql_test.s' doesn't exist

Therefor Error 1064 is the invalid syntax. You only need to create an empty test database because otherwise only errors with a wrong FROM part would appear (here for example the database is needed in order to get a valid syntax check result: ‘select asdf from s where x and if;).

As far as i tested it works fine (Version Mysql 5.5).

Here a complete bash script vesion:

#!/bin/bash

source_dir=${1};
database="mysql_test";
mysql_args="-h127.0.0.1";

mysql $mysql_args -B -e "DROP DATABASE IF EXISTS $database; CREATE DATABASE $database;";
for file in `find $source_dir -name "*.sql"`; do
    lint_result=`mysql $mysql_args $database -f -b < $file 2>&1`;
    if [ "`echo $lint_result | sed -r "s/ERROR ([0-9]*).*/1/g"`" = "1064" ]; then
        echo -e "Syntax error in file ${file}:n${lint_result}" && exit 1;
    fi;
done

SQL queries are easy to learn and reuse.

The difficulty of reading and understanding current SQL queries is known as query interpretation. It’s frequently as difficult as Query Composition, which entails writing a new query.

SQL Syntax Checker validates and marks any errors in your SQL queries.

How to Validate Syntax and Disable Statement Execution

Before executing SQL on your production database server, you can run a SQL syntax check without connecting to the database server and look for syntax issues.
The following are supported by the database: Oracle (PLSQL), SQL Server, MySQL, DB2, and Access are all examples of database management systems.
When you’re debugging and come across any syntax that’s part of a long query and wants to validate it, all you have to do is use Syntax.

Using SQL Queries to Create Visualizations

Many individuals have tried but failed to create a successful parser due to the intricacy of the SQL grammar and dialicts. Our parser reduces the problems of deciphering SQL grammar. The parsing logic generates an abstract syntax tree (AST) containing «raw» or optionally qualified table and column IDs.

AST Tree Algorithm

The parsing stage entails breaking down the components of a SQL statement into a data structure that may be processed by subsequent algorithms. The database only parses a statement when the application tells it to. Therefore only the application, not the database, may reduce the number of parses. Various utility function analyze the AST tree to identify the components:

  1. what tables appear in the query?
  2. what columns appear in the query, per clause?
  3. what is the table/column lineage of a query?
  4. what sets of columns does a query compare for equality?

SQL is the Language used to Communicate with Databases

SQL, SQL Server, MySQL, PostgreSQL, Oracle, and so on. You want to learn SQL, but you’re intimidated by the number of keywords and don’t know where to begin. Let’s go over the definitions for each of these terms.

A database is a type of computer program that stores and processes vast volumes of information. Database vendors come in a variety of shapes and sizes. Database products from different vendors include PostgreSQL, MySQL, Oracle, and SQL Server. The programming language SQL is used to communicate with these databases, and each database product has its SQL variant. These variations are referred to as SQL dialects.

In this article, we will look at the 2 different SQL syntax checker tools that help to find the syntax errors of the queries without executing them.

What is a SQL syntax checker?

SQL syntax checker tools validate SQL syntax or indicate the incorrect syntax errors if it exists. These tools can
be helpful to determine the syntax errors without executing the whole query. The following 2 tools can be used to
validate the syntax of our T-SQL queries:

  • SQL Server Management Studio (SSMS)
  • SQL Fiddle

What is the query parsing in SQL Server?

When we submit a query in SQL Server to execute, it performs 3 essential phases during the execution of the query:

  • Parse: In this phase, the Query Parser checks and validates the syntax of the SQL statement and generates a parse tree of the query. The parse tree is sent to the next stage for processing
  • Compile: In this phase, the query optimizer generates an execution plan for the query
  • Execute: In this final stage, the storage engine executes the SQL statements

How to validate query syntax with SQL Server Management Studio (SSMS)

SQL Server Management Studio (SSMS) is an advanced integrated development tool to manage, administrate, and
configure SQL Server and it also offers a query editor option to develop and execute T-SQL queries. We can find a Parse button on the query editor toolbar of SSMS, that only checks the syntax of the selected statement or all
statements that are given by the users. So that, we can use SSMS as a SQL syntax checker tool.

How to use the parse button in SQL Server Management Studio

Here we need to take into account that, when we parse a query the compile and execute phases are not performed. In the following example, we will check the syntax of a very simple query. To validate a query syntax consists of only 2 simple steps:

  • Paste or write query into the query panel
  • Click the parse button or press the Control + F5 key combination

Validate the syntax of a query in SQL syntax checker

As seen, the query syntax has been validated successfully. Now we will remove the FROM clause of the statement and re-parse the query.

Checks the syntax of a query in SSMS

After the re-parsing of the query, SQL Server returns an incorrect syntax error. Another option to check the syntax of the queries is using the SET PARSE ONLY command. This command configures the session into parsing mode.

SET PARSEONLY ON

GO

SELECT FirstName,

MiddleName,LastName

FROM Person.Person

Usage details of the SET PARSEONLY command

SQL Fiddle

SQL Fiddle is an online web application that can be used to practice or share queries with their schema build script for different database systems.

How we can use SQL Fiddle as SQL Syntax checker

Besides this, we can use SQL Fiddle as a SQL syntax checker but we need to create all objects that are placed in the query. For example in this sample query, we can build the schema and execute the query.

SQL Fiddle can show the execution plan of a query

At the same time, it shows the execution plan of a query after its execution.

How to compile queries with no execute: SET NOEXEC ON command

After enabling the NOEXEC option for a session, SQL Server parses and compiles each statement of the query but it
does not execute the query. The advantage of this command is to perform the parse and compile phases. NOEXEC option
provides the deferred name resolution, so it controls only the referenced if one or more referenced objects in the
batch don’t exist, no error will be thrown. We will explain this concept with a very simple example. In the example
query, everything is okay because the table and columns exist and syntax is also valid

SET NOEXEC ON

GO

SELECT FirstName,

MiddleName,LastName

FROM Person.Person

GROUP BY FirstName,

MiddleName,LastName

SET NOEXEC ON function usage

In the following example, the table does not exist but the query is validated but not compiled.

SELECT FirstName,

MiddleName,LastName

FROM Person.Person_NotExist

GROUP BY FirstName,

MiddleName,LastName

SET NOEXEC ON usage for non-exists tables

In this last example, SQL Server does not find the referenced objects so it will return an error.

SET NOEXEC ON

GO

    SELECT FirstName1,dbo.NotExistsFunction,

MiddleName,LastName

FROM Person.Person

GROUP BY FirstName,

MiddleName,LastName

SET NOEXEC ON returns an error

When we only parse the following query the result will return successfully but the syntax of the query is invalid
because of the missing column names after the group by.

SELECT FirstName,

MiddleName,LastName

FROM Person.Person

GROUP BY MiddleName

Parsing T-SQL query without execute

Despite that, after enabling the SET NOEXEC option, the query result will return an error.

SET NOEXEC ON command returns an error

This example shows the NOEXEC and PARSEONLY option differences. When we correct the misspelling of the syntax, SQL
Server does not return any error.

SET NOEXEC ON

GO

SELECT FirstName,

MiddleName,LastName

FROM Person.Person

GROUP BY FirstName,

MiddleName,LastName

How the SET NOEXEC ON command works

Another key point about the SET NOEXEC command is related to the cached execution plans. SQL Server stores the
execution plan of the executed queries in the plan cache. When we execute a query after enabling the NOEXEC option
and if this query is not returned any error, the execution plan of the query will be stored in the plan cache. Let’s
look at this working mechanism with an example. Firstly, we will clear the plan cache data of the example query if
it exists. To do this, we will execute the following query and find the plan cache details.

SELECT *

FROM sys.dm_exec_cached_plans

CROSS APPLY sys.dm_exec_sql_text(plan_handle)

WHERE usecounts > 0 AND

        text like ‘%SELECT FirstName,

MiddleName,LastName

FROM%’ AND text NOT LIKE ‘%sys.dm_exec_cached_plans%’

ORDER BY usecounts DESC;

Listing cached execution plans in SQL Server

As a second step, we will drop the execution plan that is stored for the sample query. We will pass the plan handle
data as a parameter to the DBCC FREEPROCCACHE.

DBCC FREEPROCCACHE(0x06001200A94F9D0C203F93A87B02000001000000000000000000000000000000000000000000000000000000)

Dropping a single cached plan of a query

Before executing the query, we can create an extended event session to observe the query compilation event. This extended
event must include the query_pre_execution_showplan. This event captures the SQL statement is compiled. At the same
time, this event shows the execution plan in an XML format.

SET NOEXEC ON

GO

SELECT FirstName,

MiddleName,LastName

FROM Person.Person

GROUP BY FirstName,

MiddleName,LastName

Using the Extended Events to monitor a query compilation

As we have explained, after enabling the NOEXEC command the query is compiled by the query optimizer.

Conclusion

In this article, we have looked at two different SQL syntax checker tools to validate our queries without executing
them.

  • Author
  • Recent Posts

Esat Erkec

Esat Erkec is a SQL Server professional who began his career 8+ years ago as a Software Developer. He is a SQL Server Microsoft Certified Solutions Expert.

Most of his career has been focused on SQL Server Database Administration and Development. His current interests are in database administration and Business Intelligence. You can find him on LinkedIn.

View all posts by Esat Erkec

Esat Erkec

I need an online sql query syntax validator.

I searched online but didn’t find anything good.

I saw the references in this question too:

Syntax Checker and Validator for SQL?

cнŝdk's user avatar

cнŝdk

30.9k7 gold badges55 silver badges76 bronze badges

asked Apr 10, 2014 at 1:55

sa_nyc's user avatar

4

SQLFiddle will let you test out your queries, while it doesn’t explicitly correct syntax etc. per se it does let you play around with the script and will definitely let you know if things are working or not.

cнŝdk's user avatar

cнŝdk

30.9k7 gold badges55 silver badges76 bronze badges

answered Apr 10, 2014 at 2:01

serakfalcon's user avatar

serakfalconserakfalcon

3,4711 gold badge22 silver badges33 bronze badges

9

A lot of people, including me, use sqlfiddle.com to test SQL.

answered Apr 10, 2014 at 2:00

DeanOC's user avatar

DeanOCDeanOC

7,0826 gold badges45 silver badges55 bronze badges

1

Как найти ошибку в SQL-запросе

SQL-запрос — это то, что либо работает хорошо, либо не работает вообще, частично он никак работать не может, в отличие, например, от того же PHP. Как следствие, найти ошибку в SQL-запросе, просто рассматривая его — трудно, особенно если этот запрос снабжён целой кучей JOIN и UNION. Однако, в этой статье я расскажу о методе поиска ошибок в SQL-запросе.

Поскольку обычно в SQL-запрос подставляются какие-то переменные в PHP, то необходимо его сначала вывести. Сделать это можно, например, так:

<?php
  $a = 5;
  $query = "SELECT FROM `table` WHERE `id` = '$a'";
  $result_set = $mysqli->query($query); // Не работает
  echo $query; // Выводим запрос, который отправляется
?>

В результате, скрипт выведет такой запрос: SELECT FROM `table` WHERE `id` = ‘5’. Теперь чтобы найти ошибку в нём, надо зайти в phpMyAdmin, открыть базу данных, с которой происходит работа, открыть вкладку «SQL» и попытаться выполнить запрос.

И вот здесь уже ошибка будет показана, не в самой понятной форме (иногда прямо точно описывает ошибку), но она будет. Вот что написал phpMyAdmin: «#1064 — 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 ‘FROM `table` WHERE `id` = ‘5’ ORDER BY `table`.`id` ASC LIMIT 0, 30′ at line 1«. Это означает, что ошибка рядом с FROM. Присматриваемся к этому выделенному нами небольшому участку и обнаруживаем, что мы забыли поставить «*«. Исправляем сразу в phpMyAdmin эту ошибку, убеждаемся, что запрос сработал и после этого идём исправлять ошибку уже в коде.

С помощью этого метода я нахожу абсолютно все ошибки в SQL-запросе, которые мне не удаётся обнаружить непосредственно при осмотре в PHP-коде.

Надеюсь, теперь и Вы сможете найти ошибку в любом SQL-запросе.

  • Создано 01.05.2013 10:54:01


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти сохраненные пароли в браузерах
  • Как найти производную по градиенту
  • Как на андроиде найти свою папку
  • Канал башкортостан 24 как найти
  • Как найти разность фаз для двух точек

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии