Ошибка 1064 mysql как исправить

When issuing a command to MySQL, I'm getting error #1064 "syntax error". What does it mean? How can I fix it?

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,13021 gold badges83 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

5454 silver badges16 bronze badges

3

If you’ve been using WordPress for a while, you may have decided to get into more advanced database management. This often involves using the MySQL command line, which can, in turn, lead to confusing problems such as MySQL 1064 errors.

Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.

In this post, we’ll cover the various possible causes of the MySQL 1064 error. Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.

Let’s get started!

Why the MySQL 1064 Error Occurs

The MySQL 1064 error is a syntax error. This means the reason there’s a problem is because MySQL doesn’t understand what you’re asking it to do. However, there are many different situations that can lead to this type of miscommunication between you and your database.

The simplest cause is that you’ve made a mistake while typing in a command and MySQL can’t understand your request. Alternatively, you may be attempting to use outdated or even obsolete commands that can’t be read.

In other cases, you may have attempted to include a ‘reserved word’ in one of your commands. Reserved words are terms that can only be used in specific contexts in MySQL. If you attempt to use them in other ways, you’ll be faced with an error.

It’s also possible that there is some data missing from your database. When you make a request via MySQL which references data that isn’t where it’s supposed to be, you’ll also see the 1064 error. Finally, transferring your WordPress database to another server can also lead to the same issue.

As you can see, there are many potential causes for this problem, which can make it tricky to resolve. Unless you’re in the process of moving your database or taking some other action that points to a specific cause, you’ll likely need to try a few different solutions before you land on the right one. Fortunately, none of them are too difficult to execute, as we’ll see next.

Oh no, you’re getting the MySQL 1064 Error…😭 Don’t despair! Here are 5 proven solutions to get it fixed immediately 🙏Click to Tweet

How to Fix the MySQL 1064 Error (5 Methods)

If you already have an idea of what’s causing your MySQL 1064 error, you can simply skip down to the resolution for your specific situation. However, if you’re not sure why the error has occurred, the simplest strategy is to try the easiest solution first.

In that case, we’d suggest testing out the five most likely fixes in the following order.

1. Correct Mistyped Commands

The good thing about MySQL typos is that they’re the simplest explanation for syntax issues such as the 1064 error. Unfortunately, they can also be the most tedious to correct. Generally speaking, your best option is to manually proofread your code and look for any mistakes you may have made.

We suggest using the MySQL Manual as a reference while you do so, double-checking anything you’re not sure about. As you might imagine, this can get pretty time-consuming, especially if you’ve been working in the MySQL command line for a while or if you’re new to this task.

An alternative to manually checking your work is to employ a tool such as EverSQL:

MySQL 1064 Error: EverSQL syntax checker

EverSQL syntax checker

With this solution, you can simply input your MySQL to check for errors automatically. However, keep in mind that these platforms aren’t always perfect and you may still want to validate the results yourself.

2. Replace Obsolete Commands

As platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. MySQL is no exception. If you’re working on your database following a recent update or have referenced an outdated source during your work, it’s possible that one or more of your commands are no longer valid.

You can check to see whether this is the case using the MySQL Reference Manual. You’ll find mentions of commands that have been made obsolete by each MySQL version in the relevant sections:

MySQL 1064 Error: Manually removing obsolete commands

Manually removing obsolete commands

Once you’ve determined which command is likely causing the problem, you can simply use the ‘find and replace’ function to remove the obsolete command and add in the new version. For example, if you were using storage_engine and find that it no longer works, you could simply replace all instances with the new default_storage_engine command.

3. Designate Reserved Words

In MySQL, using a reserved word out of context will result in a syntax error, as it will be interpreted as incorrect. However, you can still use reserved words however you please by containing them within backticks, like this: `select`

Each version of MySQL has its own reserved words, which you can read up on in the MySQL Reference Manual. A quick find and replace should enable you to resolve this issue if you think it may be causing your 1064 error.

4. Add Missing Data

If your latest MySQL query attempts to reference information in a database and can’t find it, you’re obviously going to run into problems. In the event that none of the preceding solutions resolves your MySQL 1064 error, it may be time to go looking for missing data.

Unfortunately, this is another solution that can be quite tedious and has to be done by hand. The best thing you can do in this situation is to work backward, starting with your most recent query. Check each database it references, and make sure all the correct information is present. Then move on to the next most recent query, until you come to the one that’s missing some data.

5. Use Compatibility Mode to Transfer WordPress Databases

This final 1064 error solution isn’t as straightforward as the others on our list. However, if you’re migrating your WordPress site to a new host or otherwise moving it to a different server, you’ll need to take extra steps to avoid causing problems with your database.

The simplest solution is to use a migration plugin that includes a compatibility mode, such as WP Migrate DB:

WP Migrate DB WordPress plugin

WP Migrate DB WordPress plugin

This will enable an auto-detection feature that will make sure your latest site backup and database are compatible with multiple versions of MySQL. You can access the compatibility mode setting by navigating to Tools > Migrate DB > Advanced Options:

WP Migrate DB settings

WP Migrate DB settings

Check the box next to Compatible with older versions of MySQL before starting your site migration. This way, you should be able to avoid any issues during the process.

Summary

Database errors can throw a wrench in your plans, and may even compromise your website’s stability. Knowing how to resolve issues such as the MySQL 1064 error can help you react quickly, and minimize downtime on your site.

There are five methods you can try to fix the MySQL 1064 error when you encounter it, depending on its most likely cause:

  1. Correct mistyped commands.
  2. Replace obsolete commands.
  3. Designate reserved words.
  4. Add missing data.
  5. Transfer WordPress databases in compatibility mode.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

If you’ve been using WordPress for a while, you may have decided to get into more advanced database management. This often involves using the MySQL command line, which can, in turn, lead to confusing problems such as MySQL 1064 errors.

Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.

In this post, we’ll cover the various possible causes of the MySQL 1064 error. Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.

Let’s get started!

Why the MySQL 1064 Error Occurs

The MySQL 1064 error is a syntax error. This means the reason there’s a problem is because MySQL doesn’t understand what you’re asking it to do. However, there are many different situations that can lead to this type of miscommunication between you and your database.

The simplest cause is that you’ve made a mistake while typing in a command and MySQL can’t understand your request. Alternatively, you may be attempting to use outdated or even obsolete commands that can’t be read.

In other cases, you may have attempted to include a ‘reserved word’ in one of your commands. Reserved words are terms that can only be used in specific contexts in MySQL. If you attempt to use them in other ways, you’ll be faced with an error.

It’s also possible that there is some data missing from your database. When you make a request via MySQL which references data that isn’t where it’s supposed to be, you’ll also see the 1064 error. Finally, transferring your WordPress database to another server can also lead to the same issue.

As you can see, there are many potential causes for this problem, which can make it tricky to resolve. Unless you’re in the process of moving your database or taking some other action that points to a specific cause, you’ll likely need to try a few different solutions before you land on the right one. Fortunately, none of them are too difficult to execute, as we’ll see next.

Oh no, you’re getting the MySQL 1064 Error…😭 Don’t despair! Here are 5 proven solutions to get it fixed immediately 🙏Click to Tweet

How to Fix the MySQL 1064 Error (5 Methods)

If you already have an idea of what’s causing your MySQL 1064 error, you can simply skip down to the resolution for your specific situation. However, if you’re not sure why the error has occurred, the simplest strategy is to try the easiest solution first.

In that case, we’d suggest testing out the five most likely fixes in the following order.

1. Correct Mistyped Commands

The good thing about MySQL typos is that they’re the simplest explanation for syntax issues such as the 1064 error. Unfortunately, they can also be the most tedious to correct. Generally speaking, your best option is to manually proofread your code and look for any mistakes you may have made.

We suggest using the MySQL Manual as a reference while you do so, double-checking anything you’re not sure about. As you might imagine, this can get pretty time-consuming, especially if you’ve been working in the MySQL command line for a while or if you’re new to this task.

An alternative to manually checking your work is to employ a tool such as EverSQL:

MySQL 1064 Error: EverSQL syntax checker

EverSQL syntax checker

With this solution, you can simply input your MySQL to check for errors automatically. However, keep in mind that these platforms aren’t always perfect and you may still want to validate the results yourself.

2. Replace Obsolete Commands

As platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. MySQL is no exception. If you’re working on your database following a recent update or have referenced an outdated source during your work, it’s possible that one or more of your commands are no longer valid.

You can check to see whether this is the case using the MySQL Reference Manual. You’ll find mentions of commands that have been made obsolete by each MySQL version in the relevant sections:

MySQL 1064 Error: Manually removing obsolete commands

Manually removing obsolete commands

Once you’ve determined which command is likely causing the problem, you can simply use the ‘find and replace’ function to remove the obsolete command and add in the new version. For example, if you were using storage_engine and find that it no longer works, you could simply replace all instances with the new default_storage_engine command.

3. Designate Reserved Words

In MySQL, using a reserved word out of context will result in a syntax error, as it will be interpreted as incorrect. However, you can still use reserved words however you please by containing them within backticks, like this: `select`

Each version of MySQL has its own reserved words, which you can read up on in the MySQL Reference Manual. A quick find and replace should enable you to resolve this issue if you think it may be causing your 1064 error.

4. Add Missing Data

If your latest MySQL query attempts to reference information in a database and can’t find it, you’re obviously going to run into problems. In the event that none of the preceding solutions resolves your MySQL 1064 error, it may be time to go looking for missing data.

Unfortunately, this is another solution that can be quite tedious and has to be done by hand. The best thing you can do in this situation is to work backward, starting with your most recent query. Check each database it references, and make sure all the correct information is present. Then move on to the next most recent query, until you come to the one that’s missing some data.

5. Use Compatibility Mode to Transfer WordPress Databases

This final 1064 error solution isn’t as straightforward as the others on our list. However, if you’re migrating your WordPress site to a new host or otherwise moving it to a different server, you’ll need to take extra steps to avoid causing problems with your database.

The simplest solution is to use a migration plugin that includes a compatibility mode, such as WP Migrate DB:

WP Migrate DB WordPress plugin

WP Migrate DB WordPress plugin

This will enable an auto-detection feature that will make sure your latest site backup and database are compatible with multiple versions of MySQL. You can access the compatibility mode setting by navigating to Tools > Migrate DB > Advanced Options:

WP Migrate DB settings

WP Migrate DB settings

Check the box next to Compatible with older versions of MySQL before starting your site migration. This way, you should be able to avoid any issues during the process.

Summary

Database errors can throw a wrench in your plans, and may even compromise your website’s stability. Knowing how to resolve issues such as the MySQL 1064 error can help you react quickly, and minimize downtime on your site.

There are five methods you can try to fix the MySQL 1064 error when you encounter it, depending on its most likely cause:

  1. Correct mistyped commands.
  2. Replace obsolete commands.
  3. Designate reserved words.
  4. Add missing data.
  5. Transfer WordPress databases in compatibility mode.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

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.

Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.


Pooja Chaudhary

Read time 5 minutes

At first, the syntax errors seem very tedious and cryptic while working with SQL database programs. But, at a closer glance, one can easily understand the errors as they are descriptive enough about the problem that finding possible solutions becomes a step easier. Every error code has a unique 4 digits number that determines the type of error. One such SQL error code is Error: 1064 which occurs due to wrongly typed syntax of SQL queries. Let’s dig deep to know more about this error and how to fix it.

The error message with error code 1064 occurs due to the incorrect syntax of MySQL queries. In simple words, MySQL does not understand the commands that you have written. The commands are mistyped or misspelled within the MySQL environment which the database does not recognize. Say for example UPDATE is typed as UPADTE. Also, don’t get confused between syntax error and grammar error, because grammar rules are valid for a syntax error. The parser disagrees to understand the command and fails to perform a task.

Reasons for MySQL Syntax Error: 1064

The possible reasons due to which MySQL faces syntax error – 1064 are mentioned here:

  • It can occur due to mistyping the spelling of command.
  • The error can take place due to the use of outdated or depreciated commands.
  • It may happen when the specific data required by the query goes missing.
  • Due to wrong reserved words typed as they vary from version to version in MySQL.
  • This occurs due to a mistake in the spelling of the command resulting in MySQL not being able to understand it.
  • The error can take place due to the use of outdated or obsolete commands which are no longer in function.
  • It may happen when some data goes missing in the written database.
  • Due to wrong reserved words typed as they vary from version to version in MySQL. Reserve words are used for specific context only.

Instant Solution

Avail the fastest solution Kernel for MySQL Database recovery to fix SQL Syntax Error 1064. This software can quickly resolve problems related to MySQL Database.

How to Resolve Syntax Error: 1064?

When any MySQL error occurs, it indicates the problem along with a description and the way to fix it. Hence, for different syntax errors, it shows different fix solutions. Some of them are mentioned here, follow them according to the syntax error that is troubling you:

Fix 1: Mistyped Commands

The foremost reason due to which 1064 error occurs when you type incorrect spelling of a command or typos.

Example: UDPATE table emp set id = 0;
The UPDATE command is mistyped.

Solution to Fix

To fix the spelling errors mistyped commands and typos you must recheck before executing them. In case, you are unable to recall the correct syntax; we advise you to refer MySQL Manual and search for the syntax for the version you’re using. The error will get resolved if you replace all the typos and mistyped commands with the correct syntax.

You can also try IDEs and MySQL tools that help you with MySQL syntax errors by highlighting or pop-up alerts when you execute the query. If the IDE that you installed is lacking the feature of detecting syntax errors, look for a plugin that is designed for this purpose to debug the issue.

Fix 2: Reserved Words

Reserved words vary from one MySQL version to another as every version has its list of keywords that are reserved. The reserved words are for performing a specific task and are used for different purposes in the MySQL database engine. The error 1064 might pop up in cases when you are not using the right keyword meant for serving the specific function, or the version of MySQL is not meeting the exact requirements for using the particular keyword.

For example, Create Table alter (name, id);

Here, alter is a reserved word, but it cannot be used as it needs some special requirements. Let’s know how to use a reserved keyword in a query.

Solution to Fix

To use alter in MySQL query as you need to fulfill the unique requirements to call the functionality of the alter command, you cannot use it as mentioned above. You need to enclose the alter word with backticks (`), present on your keyboard just above the Tab button.`

For example: Create Table `alter` (name, id);

Fix 3: Missing Data

At times, the relevant data goes missing from the database which is required for the execution of a query. Hence, leading to 1064 error when the data is not found in the database.

For example: Select * from students where studentID = $id

Suppose if the $id not correctly filled, the above query for the server is like this:

Select * from students where studentID =
That is the reason the server pops up error 1064 because it gets confused.
Solution to Fix

You can enter the missing data using the dashboard interface of the application, which is usually done through phpMyAdmin or MySQL Workbench. The applications allow you to bring up the record and add the missing data manually to an appropriate row of the table.

Recommended: Automated Solution to Fix MySQL Database Errors

At times, the error 1064 becomes a bit tricky to resolve as it might occur due to the corruption of database files, i.e., MyIASM, .cnf, .ddl, .arm, etc. If that is the case, then you must use the professional automated solution to recover and restore database files of any MySQL server version. The best-recommended solution is the Kernel for MySQL Database recovery. The solution is highly efficient and works immediately to resolve problems caused by MySQL database files.

Concluding Words

The error 1064 seems simple to remove if you are aware of the exact cause behind the error. The manual solution may not work correctly if you do not use the correct steps to eliminate the error. You should use Kernel SQL Database Recovery software to handle each kind of error, whether physical or logical. The software will recover the complete databases with their tables, relationships, and dependencies.

When there is a syntax mistake in the SQL statement, MySQL Error Code 1064 is displayed. This indicates that MySQL does not recognise the command and issues an error. This post will show you how to work around the  MySQL Error 1064.

Understanding the MySQL Error 1064 message

In MySQL, tracing down and fixing query or command problems might take a long time, especially for beginners. Before attempting to fix the error, you must first understand how MySQL generates the error message. The example below demonstrates how to interpret MySQL’s error 1064.

Example:

Returns message:

Error Code: 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 Person' at line 2.
  • In an error message, the quotation denotes the first character of the query that MySQL is unable to perform. The quotation begins at ‘from Person’ in the example above. Because there is a comma before ‘from Person’ MySQL expects another column name in the SELECT clause rather than the keyword ‘from’ in the command.’
  • Look for the word… near ‘…’ in the error message to see where the error started. The error’s position is indicated by the first word (token) in the quotes and the last word in the quotes. Example: near ‘from Person’
  • If the error message contains … near ‘ ‘  but nothing between the quotes, MySQL does not identify where the query statement starts and ends. It could indicate that the query has unbalanced quotes (‘ or “), or that the parentheses are not balanced, or that the query is not properly terminated.

MySQL Reference Manual 

Check the MySQL Reference Manual for updated features, commands, and obsolete commands that could be contributing to MySQL Error 1064 if you’re working on a new database version. Access the MySQL Reference Handbook; in the General Information portion of each version reference manual, you’ll find the What’s New section. It informs you about new features, deprecated commands, and other database-related information.

Using tools to validate MySQL command syntax

If you are new to MySQL commands then make use of platforms like EverSQL or MySQL Syntax Checker to validate your MySQL query. Copy and paste your code into the platform and it automatically validates your query.

More Information

For more information please visit:

  • https://dev.mysql.com/doc/refman/8.0/en/
  • https://www.eversql.com/sql-syntax-check-validator/

Содержание

  1. ИТ База знаний
  2. Полезно
  3. Навигация
  4. Серверные решения
  5. Телефония
  6. Корпоративные сети
  7. SQL error 1064 – что делать?
  8. Бесплатный вводный урок на онлайн курс по Linux
  9. Использование зарезервированных слов
  10. Недостающая информация в таблице
  11. NoSQL
  12. Полезно?
  13. Почему?
  14. MySQL error 1064
  15. 1. Запрос в редакторе.
  16. 2. Перенос базы на другой сервер.
  17. 3. Некорректная работа сайта.
  18. Форум пользователей MySQL
  19. #1 22.11.2010 05:31:00
  20. ERROR 1064 (42000) Я Полный чайник
  21. #2 22.11.2010 06:42:48
  22. Re: ERROR 1064 (42000) Я Полный чайник
  23. #3 23.11.2010 01:50:30
  24. Re: ERROR 1064 (42000) Я Полный чайник
  25. #4 23.11.2010 01:59:31
  26. Re: ERROR 1064 (42000) Я Полный чайник
  27. #5 23.11.2010 15:28:00
  28. Re: ERROR 1064 (42000) Я Полный чайник

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Навигация

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

SQL error 1064 – что делать?

Вам когда-нибудь приходилось видеть ошибку 1064 при работе с MySQL? Причем она указывает на некие синтаксические ошибки в SQL запросе, и эти ошибки могут быть совсем неочевидны – подробнее расскажем ниже.

Бесплатный вводный урок на онлайн курс по Linux

Мы собрали концентрат самых востребованных знаний, которые позволят начать карьеру администраторов Linux, расширить текущие знания и сделать уверенный шаг в DevOps

Использование зарезервированных слов

У каждой версии MySQL есть свой список зарезервированных слов – эти слова используются для особых задач или особых функций внутри движка MySQL. При попытке использовать какие-то из них, вы получите ту самую ошибку 1064. К примеру, ниже пример SQL запроса, который использует зарезервированное слово в качестве имени таблицы.

Как этого избежать? Просто! Только потому что слово alter зарезервировано, это не значит, что его нельзя использовать – нужно просто по-особенному приготовить! Чтобы движок MySQL не воспринимал это слово как команду, мы будем просто использовать кавычки и оно взлетит:

Недостающая информация в таблице

Иногда какой-то части информации в таблице нет и это может вызвать эту ошибку, если запрос обращался к этим данным. К примеру, если в таблице был список сотрудников, и каждому был присвоен ID, было бы логично предположить, что запрос будет вызывать запись сотрудника вместе с номером ID, например:

Если пресловутый $id никогда не был правильно указан, запрос будет выглядеть для MySQL сервера следующим образом:

Т.к запрос по сути пустой, движок MySQL будет выдавать ту самую ошибку 1064. Исправляется это следующим образом – вам нужно каким-то образом вызвать конкретную запись и добавить недостающую информацию, причем сделать это не так просто: если пытаться вызвать запись по уникальному номеру, скорее всего вы увидите точно такую ошибку. Можно с помощью phpMyAdmin вручную выбрать необходимую строку и добавить нужную информацию.

Опечатки в командах

Одной из самых частых причин ошибки 1064 являются опечатки. И иногда можно десять раз посмотреть на команду и не увидеть опечатки – как пример ниже с командой UPDATE:

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

Устаревшие команды

Некоторые команды устарели, и в новых версиях MySQL начинают выдавать хорошо знакомую нам ошибку. К примеру, команда ‘TYPE’ была признана устаревшей в MySQL 4.1 и была полностью удалена в MySQL 5.1, где при попытке использовать ее вы можете видеть ту самую ошибку. Вместо нее необходимо использовать команду ‘ENGINE’.

Ниже неверный вариант:

А вот правильный, модный и современный вариант (как оно должно быть, чтобы не было ошибки):

Заключение

Как можно видеть, для одной несчастной ошибки, указывающей на синтаксис, может быть целый ряд разных причин. Так что когда вы видите подобную ошибку – вспомните эту статью и проверьте все возможные варианты ?

NoSQL

Научись создавать архитектуру хранения данных, управлять ею и автоматизировать рутинные процессы

Полезно?

Почему?

😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.

😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.

Источник

MySQL error 1064

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

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

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

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

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

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

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

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

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

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

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

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

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

Редко бываю случаи, когда перенос идет на старый (

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

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

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

Значит ваш дамп содержит 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.

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

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

Источник

Форум пользователей MySQL

Задавайте вопросы, мы ответим

Страниц: 1

#1 22.11.2010 05:31:00

ERROR 1064 (42000) Я Полный чайник

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

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 ‘IF EXISTS’ at line 1

Стоит MySQL 5.1
Импортирую схему именно для MySQL, правда, для какой версии — точно не знаю

Подскажите, где ошибка в синтаксисе, и как он должен выглядеть, либо киньте ссылку, на поддерживаемые функции данной версии и их описание, пожалуйста

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

Отредактированно NewUse (22.11.2010 05:31:34)

#2 22.11.2010 06:42:48

Re: ERROR 1064 (42000) Я Полный чайник

#3 23.11.2010 01:50:30

Re: ERROR 1064 (42000) Я Полный чайник

Да, спасибо, заработало, помогите, пожалуйста исправить ещё одну ошибочку такого же типа (несовместимость версий):
Сайтик под предположительно php4+MySQL — версия ранняя 2004г или ранее:

while ( $row = $query -> fetchRow ( ) ) <
unset ( $ROW ) ;
$row [ packet ] = «$row[packet] n » ;
$TMP_ROW = «» » . $INDEX_PAGE [ edit ] . » » border=0> n » ;
if ( $row [ action ] > 0 ) <
$TMP_ROW .= » | » » . $INDEX_PAGE [ price ] . » » border=0> n » ;
>
$TMP_ROW .= » | » » . $NIBS_TEXT [ delete ] . » » border=0> n » ;
$row [ action ] = $TMP_ROW ;
$count = $db -> getRow ( «select count($username) as $username from users where gid=$row[gid]» ) ;
$row [ num_users ] = $count [ $username ] ;
$TOTAL_USER += $count [ $username ] ;
$TRAF_ARRAY = $db -> GetRow ( «select sum(in_bytes) as in_bytes, sum(out_bytes) as out_bytes from » .NIBS_ACCT_TABLE. » where gid=» . $row [ gid ] ) ;
$row [ gid ] = round ( $TRAF_ARRAY [ in_bytes ] / ( 1024 * 1024 ) , $ROUND_DIGIT ) . «/» ;
$row [ gid ] .= round ( $TRAF_ARRAY [ out_bytes ] / ( 1024 * 1024 ) , $ROUND_DIGIT ) ;
$TOTAL_IN += $TRAF_ARRAY [ in_bytes ] ;
$TOTAL_OUT += $TRAF_ARRAY [ out_bytes ] ;
while ( list ( $key , $val ) = each ( $row ) ) <
if ( $HEADER ) <
$TMP_HEADER [ ] = array ( VARS => $NIBS_TEXT [ $key ] ,
TD_CLR => HDR_CLR,
TH => true ) ;
>
$ROW [ ] = array ( VARS => $val ,
TD_PAR => «align=middle» ,
TD_CLR => DEF_CLR ) ;
>
if ( $HEADER ) <
$HEADER = false ;
$ARRAY [ ] = $TMP_HEADER ;
>
$ARRAY [ ] = $ROW ;

PHP Fatal error: Call to a member function fetchRow() on a non-object in /usr/local/www/data/index.php on line 13

#4 23.11.2010 01:59:31

Re: ERROR 1064 (42000) Я Полный чайник

Как следует из текста ошибки — Вы пытаетесь вызвать метод у сущности,
не являющейся объектом. Задавайте, пожалуйста, вопросы по PHP на
webew.ru.

#5 23.11.2010 15:28:00

Re: ERROR 1064 (42000) Я Полный чайник

Спасибо, а такой синтаксис в MySQL5 допустим?

Источник

SQL Syntax errors are some of the frantic error which can really affect the workability of the SQL database. However, they can easily be fixed once you figure the reason for the occurrence. One such error is MySQL Error 1064 which takes place due to the incorrect syntax typing in SQL queries. Let’s discuss more about error 1064.

The SQL error code 1064 takes place due to the input of illogical command in within the Structured Query Language or SQL. Syntax errors are just like any grammar mistake in any language. So, when you input some incorrect commands the SQL could not understand what you are saying are ends up with errors like 1064. The below-given screenshot will help you to identify MySQL error 1064.

error 1064

Causes for MySQL Error 1064

The most popular reason for the occurrence of this errors are as follows:

  1. Mistyping in the command lines is the prime reason for this error.
  2. Also, outdated or deprecated commands can lead to this error.
  3. If some data goes missing and query specifically requires that data, error 1064 pops up.
  4. Usage of different Reserved words is one of the reasons as different versions of MySQL use different reserved words.

Easy Workaround to Fix SQL Syntax Error 1064

When MySQL encounter some fault, it automatically indicates the problem description along with the method to fix it. So, when MySQL faces syntax error 1064, it provides multiple methods to fix it. Below I have discussed the simplest yet most effective methods to eradicate the problem.

Fixing Mistyped Commands

Like we discussed the most common reason for the occurrence of this error is mistype or wrong commands. Example, “UPDATE table emp set id=0”, here the update is mistyped. So to fix it all we need to do is correct the wrong commands. Recheck all the commands and spelling before executing once again. Referring to your MySQL manual is highly recommended as all the syntax are different for all the versions. The error will be resolved when you replace all the mistyped commands with the correct one. You can also take help of IDEs and SQL tools if you are having some problem with fixing manually.

Reserved Words

Reserved words vary from versions to versions of MySQL as every version have there own listing of keywords. Basically reserved keywords are used to perform a specific task and are used for different intents in the MySQL database. Example “Create Table alter (name, id)”, in this “alter” is the reserved word but it is restricted to be used only with some special requirement.

Hence to fix this type of problems all you need to use the special requirements to call the functionality in the MySQL query. In the case of “alter,” you need to use (`) to make it work.

Missing Data

Sometimes when the data get lost from the SQL database and that data is required for the execution of the query errors 1064 is generated. Therefore to fix all you need to do is just enter the missing data using the dashboard interface of the application. It is generally done via phpMyAdmin or MySQL Workbench. These applications help you to insert the missing data manually to the exact row of the table.

Recommended Tool To Fix SQL Database Errors

Sometimes fixing errors can become tricky and might corrupt the whole database i.e. the MDF and NDF files. So, you must use a professional self-proficient automated tool to fix all type of errors of the SQL database. SQL Recovery Tool is one of the best tool out there in the market. If the database is corrupted or damaged then also you can use this tool to restore and cover all the database files. It can easily recover all the files objects including tables, views, stored procedure, programmability, triggers, etc.

A video demonstration on how to fix Recovery Pending State in SQL Server 2016, 2014, 2012 & 2008



download

Conclusion

MySQL error 1064 appears harmless but sometimes can become very tricky to fix. There are multiple reasons for the cause and multiple ways to fix SQL syntax error. But we would suggest you perform the manual fixes only if you are an experienced user, otherwise, the professional tool to fix SQL error would be a wise choice.

Понравилась статья? Поделить с друзьями:
  • Ошибка 1063 радмин впн
  • Ошибка 1062 служба не запущена
  • Ошибка 1062 при подключении к интернету как исправить
  • Ошибка 1062 при подключении к интернету windows 10
  • Ошибка 1062 пежо 308