Sql ошибка check the manual that corresponds

When issuing a command to MySQL, I’m getting error #1064 «syntax error».

  1. What does it mean?

  2. How can I fix it?

asked May 7, 2014 at 10:32

eggyal's user avatar

TL;DR

Error #1064 means that MySQL can’t understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn’t a reserved word (and, if it is, ensure that it’s properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they’re (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this «syntax» of which you speak? Is it witchcraft?

      Whilst «syntax» is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article «a» must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is «parse» that command in order to make sense of it. A «syntax error» means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It’s important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL’s grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      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 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn’t expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you’ll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we «check the manual that corresponds to our MySQL version for the right syntax to use«. Let’s do that.

      I’m using MySQL v5.6, so I’ll turn to that version’s manual entry for an UPDATE command. The very first thing on the page is the command’s grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it’s enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual’s description of what was expected at that point), virtually every syntax error can be readily identified.

    I say «virtually all», because there’s a small class of problems that aren’t quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn’t intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

3

It is late but will help others and ofcourse will save time :)
My query was working in MySQL 5.7 in local system but on live we have version MySQL 8 and query stop working.

Query:

SELECT t.*
FROM groups t
ORDER BY t.id DESC
LIMIT 10 OFFSET 0

Output in MySQL 8:

Error in query (1064): Syntax error near ‘groups t ORDER BY t.id DESC’
at line …

I came to know groups is reserved word so I have to wrap groups with « quotes or change the table name to solve this issue.

answered Jul 18, 2021 at 13:13

Muhammad Shahzad's user avatar

Muhammad ShahzadMuhammad Shahzad

9,23021 gold badges84 silver badges130 bronze badges

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can’t figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

answered Apr 19, 2017 at 10:54

Umair Malhi's user avatar

Umair MalhiUmair Malhi

5551 gold badge4 silver badges16 bronze badges

3

во первых запрос должен иметь примерно такой формат:

INSERT INTO `price` (`N`, `title`, `localsum`, `regionsum`, `rfsum`, `intersum`) VALUES  (1,'Poi',2,1000,1500,2000,4000)

обрати внимание, что кол-во полей не то, кол-во данных которые вставляются не соответствует кол-ву полей
во вторых у вас тип данных не правильный

`localsum` char(100) not null,
`regionsum` char(100) not null,
`rfsum` char(100) not null,
`intersum` char(100) not null,

эти поля должны быть int а не char
Если вы хотите именно строку, то цифры (при вставке) нужно оборачивать в кавычки

в третьих, раз `N` int not null auto_increment, то значение N можно или игнорировать при вставке, или передавать NULL

P.S. Строку вставки можно делать так:

INSERT INTO `price` SET `field`=1, `field2`=2, `field3`=3

так визуально понятней что куда вставляется

——
UPD

<?php
// соединение с базой:
chdir(dirname(__FILE__));
$dsn = 'mysql:host=localhost'.
    ';dbname=temp_development'.
    ';port='.
    ';connect_timeout=15';

$user = 'root';
$password = '123qwe#';
$db = new PDO($dsn, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);



$file = "./price.txt";# 'Poi',2,1000,1500,2000
# в файле я убрал последнее значение, т.к. для него нет соответствующей колонки в ДБ
if($fp = fopen($file, 'r'))
{
    $sql = "INSERT INTO `price` (`title`, `localsum`, `regionsum`, `rfsum`, `intersum`) VALUES ";
    $prepare = array();
    $insert = array();
    while($line = fgets($fp))
    {
        $line = trim($line);
        if(!$line)
            continue;
        # Читаю файл построчно, чтоб память не загадилась если файл содержит оч много данных

        // валидацию данных я не делаю
        array_push($prepare, implode(",", array_fill(0, 5, "?")));
        $insert = array_merge($insert, explode(",", $line));

    }
    $pr = $db->prepare($sql."( ".implode("), (", $prepare)." )");
    $pr->execute($insert);
}

этот код сгенерирует такой вот запрос в бд:

INSERT INTO `price` (`title`, `localsum`, `regionsum`, `rfsum`, `intersum`) VALUES ( ''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000'), (''Poi'','2','1000','1500','2000' )

So, you’re creating a custom SQL query to perform a task in the database. After putting the code together and running it in PHPmyAdmin it responds with a 1064 error. It may look similar to this:

1064 error message

The 1064 error displays any time you have an issue with your SQL syntax, and is often due to using reserved words, missing data in the database, or mistyped/obsolete commands. So follow along and learn more about what the 1064 error is, some likely causes, and general troubleshooting steps.

Note: Since syntax errors can be hard to locate in long queries, the following online tools can often save time by checking your code and locating issues:

  • PiliApp MySQL Syntax Check
  • EverSQL SQL Query Syntax Check & Validator

Causes for the 1064 error

  • Reserved Words
  • Missing Data
  • Mistyped Commands
  • Obsolete Commands

This may seem cryptic since it is a general error pointing to a syntax issue in the SQL Query statement. Since the 1064 error can have multiple causes, we will go over the most common things that will result in this error and show you how to fix them. Follow along so you can get your SQL queries updated and running successfully.

Using Reserved Words

Every version of MySQL has its own list of reserved words. These are words that are used for specific purposes or to perform specific functions within the MySQL engine. If you attempt to use one of these reserved words, you will receive the 1064 error. For example, below is a short SQL query that uses a reserved word as a table name.

CREATE TABLE alter (first_day DATE, last_day DATE);

How to fix it:

Just because the word alter is reserved does not mean it cannot be used, it just has special requirements to use it as the MySQL engine is trying to call the functionality for the alter command. To fix the issue, you will want to surround the word with backticks, this is usually the button just to the left of the “1” button on the keyboard. The code block below shows how the code will need to look in order to run properly.

CREATE TABLE `alter` (first_day DATE, last_day DATE);

Missing Data

Sometimes data can be missing from the database. This causes issues when the data is required for a query to complete. For example, if a database is built requiring an ID number for every student, it is reasonable to assume a query will be built to pull a student record by that ID number. Such a query would look like this:

SELECT * from students WHERE studentID = $id

If the $id is never properly filled in the code, the query would look like this to the server:

SELECT * from students WHERE studentID =

Since there is nothing there, the MySQL engine gets confused and complains via a 1064 error.

How to fix it:

Hopefully, your application will have some sort of interface that will allow you to bring up the particular record and add the missing data. This is tricky because if the missing data is the unique identifier, it will likely need that information to bring it up, thus resulting in the same error. You can also go into the database (typically within phpMyAdmin) where you can select the particular row from the appropriate table and manually add the data.

Mistyping of Commands

One of the most common causes for the 1064 error is when a SQL statement uses a mistyped command. This is very easy to do and is easily missed when troubleshooting at first. Our example shows an UPDATE command that is accidentally misspelled.

UDPATE table1 SET id = 0;

How to fix it:

Be sure to check your commands prior to running them and ensure they are all spelled correctly.

Below is the syntax for the correct query statement.

UPDATE table1 SET id = 0;

Obsolete Commands

Some commands that were deprecated (slated for removal but still allowed for a period of time) eventually go obsolete. This means that the command is no longer valid in the SQL statement. One of the more common commands is the ‘TYPE‘ command. This has been deprecated since MySQL 4.1 but was finally removed as of version 5.1, where it now gives a syntax error. The ‘TYPE‘ command has been replaced with the ‘ENGINE‘ command. Below is an example of the old version:

CREATE TABLE t (i INT) TYPE = INNODB;

This should be replaced with the new command as below:

CREATE TABLE t (i INT) ENGINE = INNODB;

For developers or sysadmins experienced with the command line, get high availability and root access for your application, service, and websites with Cloud VPS Hosting.

Error 1064 Summary

As you can see there is more than one cause for the 1064 error within MySQL code. Now, you know how to correct the issues with your SQL Syntax, so your query can run successfully. This list will be updated as more specific instances are reported.

  • Gary Vanpelt

Gary Vanpelt

Jan 14, 2023
2 min read

The «you have an error in your SQL syntax» error typically occurs when there is a problem with the SQL query being executed. Here are some steps that may help to fix the issue:

  1. Check for any typographical errors in the SQL query, such as mistyped keywords or missing punctuation.
  2. Make sure that the syntax of the query is correct and conforms to the MySQL version that you are using. You can check the manual of your specific version of MySQL for guidance on the correct syntax.
  3. Verify that all table and column names are spelled correctly and that they exist in the database.
  4. Check that the values being inserted into the query, such as string values, are properly enclosed in single or double quotes.
  5. Check if the mysql user has the correct privileges to execute the query.
  6. If you are using a prepared statement, check if you have bound the correct value types to the parameters.
  7. If the error message is occurring for a specific query, you can use the mysql client or other tools like phpmyadmin to run the query and see the exact error message and location.

It’s worth noting that this is a general troubleshooting steps, the root cause may vary in each scenario.

Common SQL syntax errors include:

  1. Misused keywords: Misusing SQL keywords, such as using «SELECT» instead of «SELECTED», can cause syntax errors. Solution: Check the spelling and capitalization of all keywords in the query.
  2. Missing punctuation: Forgetting punctuation such as commas, parentheses, or semicolons can cause a syntax error. Solution: Check the query for any missing punctuation and add it as necessary.
  3. Incorrect use of quotes: String values in SQL queries need to be enclosed in single or double quotes, if they are not, it will cause a syntax error. Solution: Make sure that string values are properly enclosed in quotes.
  4. Unbalanced Parenthesis: Parenthesis are used to group expressions in SQL, if they are not balanced it will cause a syntax error. Solution: Check that all parenthesis are properly balanced.
  5. Unknown column or table: If the column or table name is not found in the database, it will cause a syntax error. Solution: Check that the column and table names are spelled correctly and that they exist in the database.
  6. Unknown function: If the function used in the query is not recognized by the SQL server, it will cause a syntax error. Solution: Check that the function name is spelled correctly and that it exists in the MySQL version being used.
  7. Incorrect use of aggregate functions: Aggregate functions such as SUM, AVG, COUNT, etc. should be used with a GROUP BY clause, if not it will cause a syntax error. Solution: Use aggregate functions correctly with a GROUP BY clause.

It’s worth noting that this is a general troubleshooting steps, the root cause may vary in each scenario.

Related Link About The Issue:

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 ″leave″

I always get this error when i run my code 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 ″leave″ at line…

Stack OverflowJJ___

Great! You’ve successfully signed up.

Welcome back! You’ve successfully signed in.

You’ve successfully subscribed to Lxadm.com.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

Дата: 25.11.2013

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Статья ориентирована на новичков. В ней объясняется, что означает ошибка сервера MySQL №1064, рассматриваются типичные ситуации и причины возникновения этой ошибки, а также даются рекомендации по исправлению.

Рассмотрим простейший пример.

SELECT mid, time, title, artist, download, view_count, rating, vote_num FROM dle_mservice WHERE category = ‘1’ AND approve = ‘1’ ORDER BY time DESC LIMIT -10,10;
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 ‘-10,10’ at line 1

Сервер MySQL сообщает, что в первой строке нашего SQL запроса имеется синтаксическая ошибка, и в одинарных кавычках цитирует часть запроса с того места где начинается ошибка. Это очень полезное свойство, так как позволяет сразу определить место, которое сервер счел ошибочным. В данном случае это ‘-10,10’, ошибка возникает из-за того, что параметр LIMIT не может быть отрицательным числом.

Однако, бывает и так, что цитируемый кусок запроса не содержит синтаксической ошибки. Это означает, что данная часть запроса находится не на своем месте из-за чего весь запрос становится синтаксически неверным. Например, отсутствует разделитель между двумя запросами, пропущен кусок запроса, невидимый символ в дампе и т.д. Неудобством таких ситуаций является то, что сообщение об ошибке не содержит исходный запрос.
Действия по исправлению зависят от контекста возникновения ошибки. Таковых всего 3:

1. Запрос в редакторе.

Самый простейший случай — вы пишите свой запрос в редакторе. Если причина не опечатка, то:

  • Смотреть в документации синтаксис команды для вашей версии сервера MySQL.

    Обратите внимание: речь идет о версии сервера MySQL, а не клиента (phpmyadmin, workbench и т.д.). Версию сервера можно узнать выполнив команду select version();

  • В MySQL допускается использование ключевых слов в качестве имен столбцов/таблиц, но при этом их необходимо заключать в обратные кавычки (там где буква ё на клавиатуре).
    Пример:

    select order from test;
    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 ‘order from test’ at line 1
    MariaDB [test]> select `order` from test;
    +——-+
    | order |
    +——-+
    |  NULL |
    +——-+

  • По умолчанию ; разделяет команды. Если же нужно выполнить набор из нескольких инструкций как одну команду (например, при создании процедур, фунуций, триггеров), то в зависимости от используемого клиента может потребоваться переопределить разделитель с помощью DELIMITER, иначе интерпретация команды остановится на первой ; и будет ошибка синтаксиса. Пример:

    delimiter //
    create procedure test()
    begin
    set @a=1;
    select @a;
    end//

    Обратите внимание: DELIMITER это команда консольного клиента mysql, необходимость его использования зависит от того как вы передаете команду серверу. Например,:

    • mysql_query() выполняет содержимое как одну команду, добавление delimiter приведет к error 1064 с цитатой, начинающейся со слова delimiter
    • phpmyadmin удаляет слово delimiter из-за чего возникает error 1064 с цитатой, начинающейся с переопределенного разделителя
    • в MysqlQueryBrowser напротив необходимо использовать delimiter.

2. Перенос базы на другой сервер.

У вас есть дамп (т.е. файл с расширением .sql) и при попытке его импортировать вы получаете ошибку 1064. Причины:

  • В различных версиях набор ключевых слов и синтаксис может немного отличаться. Наиболее распространенный случай: команда create table, в которой ключевое слово type было заменено на engine. Например, если вы получаете ошибку:

    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 ‘TYPE=MyISAM CHARACTER SET `utf8`’ at line 29

    Это означает, что вы переносите базу в пятую версию сервера MySQL, в котором ключевое слово TYPE не поддерживается и его нужно заменить на ENGINE.

    Редко бываю случаи, когда перенос идет на старый (~3.23) сервер, который кодировки не поддерживает. Тогда ошибка будет иметь вид:

    #1064 — You have an error in your SQL syntax near ‘DEFAULT CHARACTER SET cp1251 COLLATE cp1251_general_ci’ at line 1

    Такое может произойти, если вы переносите базу с хостинга на локальный комп, где стоит древняя версия MySQL. Лучшим решением в данном случае будет не править дамп, а обновить MySQL.

  • Часто проблемы вызваны тем, что дамп делается неродными средствами MySQL (например, phpmyadmin) из-за чего в нем могут быть BOM-маркер, собственный синтаксис комментариев, завершения команды и т.д. Кроме того при использовании того же phpmyadmin возможна ситуация при которой из-за ограничения апача на размер передаваемого файла команда будет обрезана, что приведет к ошибке 1064.
    Например, если вы получаете ошибку:

    #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 ‘
    CREATE TABLE `jos_banner` (
      `bid` int(11) NOT NULL auto_increment,
      `ci‘ at line 1

    Значит ваш дамп содержит BOM-маркер. Это три байта в начале файла, помогающие программе определить что данный файл сохранен в кодировке UTF-8. Проблема в том, что MySQL пытается интерпретировать их как команду из-за чего возникает ошибка синтаксиса. Нужно открыть дамп в текстовом редакторе (например, Notepad++) и сохранить без BOM.

    Для избежания подобных проблем при создании дампа и его импорте лучше пользоваться родными средствами MySQL, см http://sqlinfo.ru/forum/viewtopic.php?id=583

3. Некорректная работа сайта.

Если во время работы сайта появляются ошибки синтаксиса, то, как правило, причина в установке вами сомнительных модулей к вашей cms. Лучшее решение — отказаться от их использования. Еще лучше предварительно проверять их работу на резервной копии.

Пример. Движок dle 7.2, поставили модуль ,вроде бы все Ок, но:

MySQL Error!
————————
The Error returned was:
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 ‘AND approve=’1‘ AND date < ‘2008-10-04 04:34:25‘ LIMIT 5’ at line 1

Error Number:
1064
SELECT id, title, date, category, alt_name, flag FROM dle_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘Приобретение и оплата скрипта ‘) AND id !=  AND approve=‘1’ AND date < ‘2008-10-04 04:34:25’ LIMIT 5

В данном примере мы видим, что причина ошибки в отсутствии значения после «id != «

Обратите внимание: из процитированного сервером MySQL куска запроса причина ошибки не ясна. Если ваша CMS не показывает весь запрос целиком, то нужно в скриптах найти место где выполняется данный запрос и вывести его на экран командой echo.

Кусок кода, который отвечает за данный запрос это

$db->query («SELECT id, title, date, category, alt_name, flag FROM « . PREFIX . «_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘$body’) AND id != «.$row[‘id’].» AND approve=’1′».$where_date.» LIMIT «.$config[‘related_number’]);

Далее можно искать откуда взялась переменная $row и почему в ней нет элемента ‘id’ и вносить исправления, но лучше отказаться от использования такого модуля (неизвестно сколько сюрпризов он еще принесет).

P.S. Если после прочтения статьи ваш вопрос с MySQL Error 1064 остался нерешенным, то задавайте его на форуме SQLinfo

Дата публикации: 25.11.2013

© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

Понравилась статья? Поделить с друзьями:
  • Sql server ошибка the login failed
  • Sql server ошибка not support the language
  • Sql server ошибка 5023 при запуске
  • Sql server ошибка 26 при удаленном соединении
  • Sql server операция create file вызвала ошибку операционной системы