Ошибка odbc sqlstate 42000 номер ошибки 1064

   Maniac

14.02.13 — 02:04

Ошибка ODBC. SQLSTATE: 42000

Номер ошибки: 1064

Описание: [MySQL][ODBC 5.1 Driver][mysqld-5.1.55-rel12.6-log]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 ‘»refresh_date»,

T1.»pricelist_id»,

T1.tablename,

T3.»short_name»,

T2.»delivery_d’ at line 2

Не могу понять что и как.

ВНешнийисточник настроен правильно! Подключение есть. Таблицы сайта 1С показывает. Все подключается.

Запрос тоже правильный! Даже конструктором открывается. Но выдает бяку и как ее вылечить не могу понять.

ВОт текст запроса в 1С

Запрос = Новый Запрос();

Запрос.Текст =

«ВЫБРАТЬ

| pricelist.refresh_date КАК ДатаОбновления,

| pricelist.pricelist_id КАК ИД_прайслиста,

| pricelist.tablename КАК Таблица,

| providers_prices.provider_id.short_name КАК Поставщик,

| providers_prices.delivery_days КАК ДниДоставки,

| providers_prices.max_days КАК ДоставкаДо

|ИЗ

| ВнешнийИсточникДанных.СайтАвтоформула.Таблица.pricelist КАК pricelist

| ЛЕВОЕ СОЕДИНЕНИЕ ВнешнийИсточникДанных.СайтАвтоформула.Таблица.providers_prices КАК providers_prices

| ПО (providers_prices.pricelist_id = pricelist.Ссылка)»;

СоответствиеПоставщиков = Запрос.Выполнить().Выгрузить();

Вот тут часть обсуждения — но результата не принесло.

http://forum.infostart.ru/forum26/topic78912/

   Maniac

1 — 14.02.13 — 02:06

Перепробовал все драйвера 32 и 64. Также подключал 5.1 и 5.2

Также пробовал сервере 2003 и на 2008.

Также пробовал 8.3 самую последнюю тестовую.

Короче болт.

При полях с прочерками — ругается хоть бы что.

Наши партнеры работают без проблем со своей 1Ской.

   zmaximka

2 — 14.02.13 — 02:10

Это ошибка платформы. не исправленная еще

   zmaximka

3 — 14.02.13 — 02:11

Пришлось делать view для работы с ВИД MySQL

   Maniac

4 — 14.02.13 — 02:13

(2) читал. с апреля 2012 года..

Судя по давности оидать исправления скорейшего не стоит.

   Maniac

5 — 14.02.13 — 02:14

(3) можно узнать что это такое?

И после него все начинает работать?

   Maniac

6 — 14.02.13 — 02:15

У нас сайт обслуживает фирма. Вот как раз директор будет на следующей неделе в Москве их созывать для обсуждения некоторых вопросов. Эта тема тоже больная и нам очень нужная.

Сейчас то у нас налажен обмен для работы магазина.

Прямое подключение по майскулю нужно для другой задачи. заливка прайсов.

   zmaximka

7 — 14.02.13 — 02:23

view это представление данных на базе запроса в СУБД. при обращении к представлению выполняется запрос к таблицам в базе данных.

   zmaximka

8 — 14.02.13 — 02:24

во внешних источниках их можно использовать так же как и таблицы

   Maniac

9 — 14.02.13 — 02:26

(7) а то технические где надо сделать? мне или на сайте? как это сделать и где. я уже разберусь. просто нужно узнать каким инструментом. а то я не понимаю где это делать.

   hhhh

10 — 14.02.13 — 02:29

СОЕДИНЕНИЕ внешних источников — это фишка 8.3, в 8.2 даже никогда и не было такого, и не будет.

   Maniac

11 — 14.02.13 — 02:29

ВОт статья.http://habrahabr.ru/post/47031/

Только я не понял, где это делать то.

на сайте программистам дать задание? или эт ов 1С делается.

   zmaximka

12 — 14.02.13 — 02:31

На стороне MySQL в твоем случае будет что то типа:

Create view vpricelist as select pricelist.refresh_date as ‘refreshdate’ , pricelist.pricelist_id as ‘id’

как то так. за синтаксис не ручаюсь

   Maniac

13 — 14.02.13 — 02:31

(10) вот у наших партнеров все работает. Они нам дали своб конфигурацию. успешно все льют и тп. Все обработки обычные. 82 платформа. только узнать почему у них так работает я конкретно не могу. прог у них в запой ушел.

а доступа удаленного нет.

   Maniac

14 — 14.02.13 — 02:32

даже без соединений все равно не пашет. я делал простые запросы. все работало только если обращение было к полям без прочерков. ну в общем это все уже я писал несколько раз.

   zmaximka

15 — 14.02.13 — 02:32

(10) ню-ню

   Maniac

16 — 14.02.13 — 02:32

(12) спасибо за направление. вот так уже понятней. Будем дальше ковырять.

   zmaximka

17 — 14.02.13 — 02:34

(10) в запросах с ВИД нельзя соединять данные из РАЗНЫХ источников. В пределах одного источника соединения работают

   Maniac

18 — 14.02.13 — 02:36

Вот видимо почему у них все работает. они на сервере сделали этот view после чего внешние источники прописанные в 1С начали нормально работать с запросами. как я понял мне тогда вообще ничего не нужно писать. дать конторе отвечающей за сайт задание выявить и сделать по таблицам эти view

   Maniac

19 — 14.02.13 — 02:41

(17) если что можно завтра с тобой как то состыковаться по скайпу Skype: shekineugeniy

Я пообщаюсь с директором. Нам проще будет привлечь на решение этой задачи и заплатить за эту вещь.

   zmaximka

20 — 14.02.13 — 02:46

какие вопросы еще остались? Скажешь админам которые сайт поддерживают что нужно вьюхи создать для таких  то таблиц причем создать так что бы в именах полей не было подчеркиваний. в ВИД вместо реальных таблиц укажешь созданые вьюхи и собственно говоря все. если что пиши в почту

   Maniac

21 — 14.02.13 — 02:49

СПАСИБО! Ок!

Напиши статью на Инфостарте с решением — с удовольствием проголосую. Думаю найдутся еще десятки а то и сотни людей которые тоже проголосуют.

  

zmaximka

22 — 14.02.13 — 02:50

чукча не писатель, чукча читатель

  

Maniac

14.02.13 — 02:04

Ошибка ODBC. SQLSTATE: 42000

Номер ошибки: 1064

Описание: [MySQL][ODBC 5.1 Driver][mysqld-5.1.55-rel12.6-log]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 ‘»refresh_date»,

T1.»pricelist_id»,

T1.tablename,

T3.»short_name»,

T2.»delivery_d’ at line 2

Не могу понять что и как.

ВНешнийисточник настроен правильно! Подключение есть. Таблицы сайта 1С показывает. Все подключается.

Запрос тоже правильный! Даже конструктором открывается. Но выдает бяку и как ее вылечить не могу понять.

ВОт текст запроса в 1С

Запрос = Новый Запрос();

Запрос.Текст =

«ВЫБРАТЬ

| pricelist.refresh_date КАК ДатаОбновления,

| pricelist.pricelist_id КАК ИД_прайслиста,

| pricelist.tablename КАК Таблица,

| providers_prices.provider_id.short_name КАК Поставщик,

| providers_prices.delivery_days КАК ДниДоставки,

| providers_prices.max_days КАК ДоставкаДо

|ИЗ

| ВнешнийИсточникДанных.СайтАвтоформула.Таблица.pricelist КАК pricelist

| ЛЕВОЕ СОЕДИНЕНИЕ ВнешнийИсточникДанных.СайтАвтоформула.Таблица.providers_prices КАК providers_prices

| ПО (providers_prices.pricelist_id = pricelist.Ссылка)»;

СоответствиеПоставщиков = Запрос.Выполнить().Выгрузить();

Вот тут часть обсуждения — но результата не принесло.

http://forum.infostart.ru/forum26/topic78912/

  

Maniac

1 — 14.02.13 — 02:06

Перепробовал все драйвера 32 и 64. Также подключал 5.1 и 5.2

Также пробовал сервере 2003 и на 2008.

Также пробовал 8.3 самую последнюю тестовую.

Короче болт.

При полях с прочерками — ругается хоть бы что.

Наши партнеры работают без проблем со своей 1Ской.

  

zmaximka

2 — 14.02.13 — 02:10

Это ошибка платформы. не исправленная еще

  

zmaximka

3 — 14.02.13 — 02:11

Пришлось делать view для работы с ВИД MySQL

  

Maniac

4 — 14.02.13 — 02:13

(2) читал. с апреля 2012 года..

Судя по давности оидать исправления скорейшего не стоит.

  

Maniac

5 — 14.02.13 — 02:14

(3) можно узнать что это такое?

И после него все начинает работать?

  

Maniac

6 — 14.02.13 — 02:15

У нас сайт обслуживает фирма. Вот как раз директор будет на следующей неделе в Москве их созывать для обсуждения некоторых вопросов. Эта тема тоже больная и нам очень нужная.

Сейчас то у нас налажен обмен для работы магазина.

Прямое подключение по майскулю нужно для другой задачи. заливка прайсов.

  

zmaximka

7 — 14.02.13 — 02:23

view это представление данных на базе запроса в СУБД. при обращении к представлению выполняется запрос к таблицам в базе данных.

  

zmaximka

8 — 14.02.13 — 02:24

во внешних источниках их можно использовать так же как и таблицы

  

Maniac

9 — 14.02.13 — 02:26

(7) а то технические где надо сделать? мне или на сайте? как это сделать и где. я уже разберусь. просто нужно узнать каким инструментом. а то я не понимаю где это делать.

  

hhhh

10 — 14.02.13 — 02:29

СОЕДИНЕНИЕ внешних источников — это фишка 8.3, в 8.2 даже никогда и не было такого, и не будет.

  

Maniac

11 — 14.02.13 — 02:29

ВОт статья.http://habrahabr.ru/post/47031/

Только я не понял, где это делать то.

на сайте программистам дать задание? или эт ов 1С делается.

  

zmaximka

12 — 14.02.13 — 02:31

На стороне MySQL в твоем случае будет что то типа:

Create view vpricelist as select pricelist.refresh_date as ‘refreshdate’ , pricelist.pricelist_id as ‘id’

как то так. за синтаксис не ручаюсь

  

Maniac

13 — 14.02.13 — 02:31

(10) вот у наших партнеров все работает. Они нам дали своб конфигурацию. успешно все льют и тп. Все обработки обычные. 82 платформа. только узнать почему у них так работает я конкретно не могу. прог у них в запой ушел.

а доступа удаленного нет.

  

Maniac

14 — 14.02.13 — 02:32

даже без соединений все равно не пашет. я делал простые запросы. все работало только если обращение было к полям без прочерков. ну в общем это все уже я писал несколько раз.

  

zmaximka

15 — 14.02.13 — 02:32

(10) ню-ню

  

Maniac

16 — 14.02.13 — 02:32

(12) спасибо за направление. вот так уже понятней. Будем дальше ковырять.

  

zmaximka

17 — 14.02.13 — 02:34

(10) в запросах с ВИД нельзя соединять данные из РАЗНЫХ источников. В пределах одного источника соединения работают

  

Maniac

18 — 14.02.13 — 02:36

Вот видимо почему у них все работает. они на сервере сделали этот view после чего внешние источники прописанные в 1С начали нормально работать с запросами. как я понял мне тогда вообще ничего не нужно писать. дать конторе отвечающей за сайт задание выявить и сделать по таблицам эти view

  

Maniac

19 — 14.02.13 — 02:41

(17) если что можно завтра с тобой как то состыковаться по скайпу Skype: shekineugeniy

Я пообщаюсь с директором. Нам проще будет привлечь на решение этой задачи и заплатить за эту вещь.

  

zmaximka

20 — 14.02.13 — 02:46

какие вопросы еще остались? Скажешь админам которые сайт поддерживают что нужно вьюхи создать для таких  то таблиц причем создать так что бы в именах полей не было подчеркиваний. в ВИД вместо реальных таблиц укажешь созданые вьюхи и собственно говоря все. если что пиши в почту

  

Maniac

21 — 14.02.13 — 02:49

СПАСИБО! Ок!

Напиши статью на Инфостарте с решением — с удовольствием проголосую. Думаю найдутся еще десятки а то и сотни людей которые тоже проголосуют.

  

zmaximka

22 — 14.02.13 — 02:50

чукча не писатель, чукча читатель

Oops!! Stuck with MySQL Error code 1064 SQL State 42000? We can help you in fixing it.

The SQL State Error 42000 occurs mainly due to the SQL syntax error or due to the outdated JDBC MySQL driver.

At Bobcares, we often get requests to fix MySQL errors, as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix MySQL errors for our customers.

Why MySQL Error code 1064 SQL State 42000 occurs?

The MySQL Error code mainly occurs due to the SQL Syntax error. It happens when MySQL is unable to validate the commands.

The Syntax Error occurs due to many factors like mistyping the commands, deprecated or missing data from the database.

In some cases, the error occurs when the JDBC driver initializes the connection.

MySQL Error code 1064 SQL State 42000

How we fix the MySQL Error code 1064?

Recently, one of our customers approached us saying that he is getting MySQL Error code 1064 SQL State 42000. On checking, we found an error in the SQL syntax.

Now, let’s see the main causes for this Error 1064 SQL State 42000 and how our Support Engineers fix them.

1. Using Reserved Words

The reserved words perform some specific functions within the MySQL engine.

Sometimes we receive the error while using the reserved words,  The error occurs when the MySQL is not meeting the exact requirements for using the particular keyword.

Create Table alter (first name, last name);

The alter is a reserved word. To fix the error 1064 with the reserved word we specify the alter word within backticks.

Create Table 'alter' (first name, last name);

2. Outdated JDBC driver

When the JDBC driver initializes the connection, it sends several commands to the MySQL server. At that time we may receive the MySQL Error code SQL State 42000.

The problem is that the commands were deprecated for some time which results in the error.

We fix the error by upgrading the JDBC MySQL driver to the latest version.

3. Mistyping and Missing of Data

The 1064 error occurs when the data is not found in the database or mistyping the commands.

In case, if the data is missing from the database, we manually add the data to the database. Also, we make sure that all the commands are spelled correctly.

[Need any assistance with SQL State 42000 Error codes? – We’ll help you]

Conclusion

In short, today we discussed in detail on MySQL Error code 1064 and saw how our Support Engineers find the fix for this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Sqlstate 42000 Is a general code that come together with other number. Most often comes with the code 1064 and is related with SQL syntax error. This kind of error has been seen reported mostly on MySQL but also on other type of databases. This happen because your command is not a valid one within the “Structured Query Language” or SQL. Syntax errors are just like grammar errors in linguistics. In the following article we will try to explain the MySQL error 1064 but not only. Also we will show other error codes that comes together with Sqlstate[42000].

Full view of my sql error code 1064:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL (or any other like MariaDb) server version for the right syntax to use near (And here is the part of the code where the error comes)

sqlstate 42000 - mysql error 1064 – you have an error in your sql syntax

sqlstate 42000 – mysql error 1064 – you have an error in your sql syntax

Other error codes related with Sqlstate 42000:

  • 1 – syntax error or access violation 1055
  • 2 – syntax error or access violation 1071 specified key was too long
  • 3 – syntax error or access violation 1066 not unique table/alias
  • 4 – syntax error or access violation 1068 multiple primary key defined

Understand and FIX MySQL error 1064 – sqlstate 42000

SQL 1064 means that MySQL can’t understand your command!

This type of error first need to be understood and after that you can fix it. The common causes of this error are:

  • Upgrading MySQL or any other database to another version
  • Using Wrong syntax that is not supported on your current version
  • Error in applying the back tick symbol or while creating a database without them can also create an error
  • Due to using reserved words
  • Particular data missing while executing a query
  • Mistyped/obsolete commands

If you see words like “near” or “at line”, you need to check for problems in those lines of the code before the command ends.

How do I Fix SQL Error Code 1064?

  1. Read the message on the error:

So in general the error tells you where the parser encountered the syntax error. MySQL also suggest how to fix it.  Check the example below …..

  1. Check the text of your command!

In some cases the PHP commands has wrong lines. Create SQL commands using programing language can be the good example of this. So you will need to check and fix those commands. Use echo, console.log(), or its equivalent to show the entire command so you can see it.

  1. Mistyping of commands

The error can occur also when you misspell a command (e.g. instead of UPDATE you write UDPATE). This can occur often since are so easy to miss. To prevent this, make sure that you review your command for any typing error before running it. There are a lot of online syntax checkers that can help to debug your queries.

  1. Check for reserved words

Reserved words are words that vary from one MySQL version to another. Every version has its list of keywords that are reserved. They are used to perform specific functions in the MySQL engine. If you read the error and identified that occurred on an object identifier, check that it isn’t a reserved word (and, if it is, be sure that it’s properly quoted). “If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.”  You can find a full list of the reserved words specific for each MySQL version and their usage requirements at MySQL.com.

  1. Obsolete commands – another reason

Another possible reason for the sqlstate 42000 MySQL error 1064 is when you use outdated commands. As Platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. A number of commands and keywords have been deprecated. This mean that they are due for removal, but still allowed for a short period of time before they turn obsolete. On cases that you have an older backup of a MySQL database that you want to import, a quick solution is to just search and replace “TYPE=InnoDB” with “ENGINE=InnoDB”.

  1. Particular data is missing while executing a query

If the relevant data missing from the database which is required for the query, you’re obviously going to run into problems.  Using phpMyAdmin or MySQL Workbench you can enter the missing data. Interface of the application allow you to add the missing data manually to an appropriate row of the table.

You have an error in your sql syntax

You have an error in your sql syntax

“You have an error in your sql syntax” – Example 1

The error code generated jointly with the statement “syntax error or access violation”, “You have an error in your SQL syntax; check the manual that corresponds to your MySQL (or any other like MariaDB) server version for the right syntax to use near” and after that the part of SQL code where the issue is. So in simple way, the error view is showing you also where is the error. For example we have the error:

“Check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('[email protected]', '[email protected],com' at line 1”

So how to understand this?

from is a keyword in SQL. You may not use it as a column name without quoting it. In MySQL, things like column names are quoted using back ticks, i.e. `from`. Or you can just rename the column.

Another example of “You have an error in your sql syntax” sqlstate 42000 – Example 2

Error:

check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 [ SELECT COUNT(*) as count,region, MONTHNAME(date) asmonth FROM tempur_stores.stats WHERE date > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND date < DATE(NOW()) GROUP BY region, MONTH(date ]

On the query:

$stmt = DB::query(Database::SELECT, 'SELECT COUNT(*) as `count`,`region`, MONTHNAME(`date`) as`month` FROM tempur_stores.stats WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) GROUP BY `region`, MONTH(`date`');

The above query is missing a closing parenthesis in the query:

$stmt = DB::query(Database::SELECT, 'SELECT COUNT(*) as `count`,`region`, MONTHNAME(`date`) as`month`

FROM tempur_stores.stats

WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK)

AND `date` < DATE(NOW())

GROUP BY `region`, MONTH(`date`');

----------  ^ right there

Just put a parenthesis ) before that apostrophe and it should work.

MariaDB error 1064 – Example 3

An example with MariaDB version issue. Trying to do example of tagging and when:

$id = Questions::create([            'body' => request('title'),            'skillset_id' => request('skillsetId'),            'tags' => ['red', 'blue']        ])->id;

Getting error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘>’$.”en”‘ = ? and `type` is null limit 1’ at line 1 (SQL: select * from `tags` where `name`->’$.”en”‘ = red and `type` is null limit 1)

Reason is that is using MariaDB and JSON columns are only supported by MySQL. Convert to MySQL to resolve the issue.

MariaDB error 1064

MariaDB error 1064

Fix error 1064 mysql 42000 while creating a database – Example 4

MySQL error 1064 can be appearing also while you are creating database using hyphen in the name like Test-Db. This can be solved by using back tick around the database name properly or remove the hyphen in the database name.

Example:

mysql> create database Test-DB;

You will get error:

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 '-DB' at line 1

Solution:

mysql> create database ` Test-DB `;

So adding back tick around the database name will solve the issue.

Transfer WordPress MySQL database to another server

Exporting WordPress database to another server can also be cause the 1064 error. Can be resolved by choosing the compatibility mode and changing the database version to the current version you’re using. Please select the compatibility mode under the advanced tab when performing a backup and after that click the auto-detect file character set when restoring the MySQL database.

Read Also

  1. Location of SQL Server Error Log File
  2. How to fix SQL Server Error 18456
  3. How to Restore Master Database

Conclusions:

The reason behind the error it’s related closely to the end of error message. We would need to see the SQL query to understand completely the issue you’re facing. So this is the reason that we can’t completely fix the MySQL error 1064 but we exposed some examples for you. You will need to review the documentation for the version of MySQL that you are having this error appear with and your syntax to fix the problem. There are multiple reasons for its cause. We suggest you perform the sqlstate 42000 error fixes if only has experience on MySQL database.

I was looking for answer for last 3 hours, and i don’t know what to do. Here is the code:

    function get_data($tablename)
    {
        try
        {
            $conn = $this->conn();
            $stmt = $conn->prepare("SELECT * FROM :tablename ORDER BY id");
            $stmt->bindParam(':tablename', $tablename, PDO::PARAM_STR);
            $stmt->execute();
            return $stmt;
        }
        catch (Exception $e)
        {
            echo "ERROR:" . $e->getMessage();
        }
    }  

And here is the error:

ERROR:SQLSTATE[42000]: Syntax error or access violation: 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 »products’ ORDER BY id’ at line 1

What I’ve done wrong?…

marc_s's user avatar

marc_s

729k175 gold badges1327 silver badges1455 bronze badges

asked Jun 8, 2013 at 8:44

SpaceBuzz's user avatar

1

As noted here (thanks @YourCommonSense), you can’t use a parameter as a table name; and if you do, one of two things will happen:

  1. With proper prepared statements, the prepared-statement module will throw an exception (and quite rightly so, as you’ve asked it to do the impossible).
  2. With emulated prepared statements, the parameter will be blindly escaped, single-quoted, and substituted in, causing an SQL syntax error. This is what’s happened here.

That’s the problem. As for solutions:

  • Reevaluate your database design. Do you really need to split data across different tables like that? If not, combine the relevant data into a single table, and query accordingly.
  • If you’re happy with the design (or can’t change it), you’ll need an ugly insecure hack like the following:

    function get_data($tablename, $acceptable_tablenames = array()) {
      /* $acceptable_tablenames is an array of strings, containing
       *  table names that you'll accept. It's your job to make sure
       *  these are safe; this is a much easier task than arbitrary
       *  sanitization.
       */
      if (array_search($tablename, $acceptable_tablenames, true) === FALSE) {
        throw new Exception("Invalid table name"); /* Improve me! */
      } else {
        /* your try/catch block with PDO stuff in it goes here
         * make sure to actually return the data
         */
      }
    }
    

    Call it as get_data($table, array("my_datatable_1", "my_datatable_2")). Credit to the post linked to at the start of my answer for inspiration.

Community's user avatar

answered Jun 8, 2013 at 9:25

michaelb958--GoFundMonica's user avatar

2

PDO escapes parameters with single quotes ('). MySql table names need to be escaped with backticks (`).

In the example provided the tablename parameter, Products, is being escaped single quotes. This is a safety feature of the PDO engine to prevent injection attacks.

Assuming that value of $tablename makes sense in applications context (eg. validating that the current user can see all the data in the specified table.).

The following would work:

function get_data($tablename)
{
    try
    {
        $conn = $this->conn();
        $stmt = $conn->prepare("SELECT * FROM `" . str_replace("`","``",$tablename) . "` ORDER BY id;");
        $stmt->execute();
        return $stmt;
    }
    catch (Exception $e)
    {
        echo "ERROR:" . $e->getMessage();
    }
}

answered Jun 8, 2013 at 8:52

squirly's user avatar

squirlysquirly

7535 silver badges13 bronze badges

5

На связке Node.js + Express + MySQL при деплое на сервер возникает ошибка в одном из маршрутов.
Если обратиться к этому маршруту то получаем ошибку

"code":"ER_PARSE_ERROR",
"errno":1064,
"sqlMessage":"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE OR REPLACE VIEW tmp AS SELECT                    TEACH.name,             ' at line 1",
"sqlState":"42000",
"index":0

но если взять код запроса из сообщения с ошибкой и вставить в Workbench то он прекрасно отработает.
Собственно сам текст запроса, в который динамически прилетают даты и ИД города. Форматирование а-ля
Workbench.

CREATE OR REPLACE VIEW tmp AS
    SELECT 
        TEACH.name,
        CAT.description,
        WRK.idTEACHER,
        LEC.idLECTURE,
        LEC.out,
        COUNT(TGFL.idTRAININGFL) AS people,
        WRK.hours
    FROM
        LECTURE LEC
            INNER JOIN
        TRAININGFL TGFL ON TGFL.idLECTURE = LEC.idLECTURE
            AND TGFL.idCITY = 1
            AND TGFL.date_attestation BETWEEN '2018-01-01' AND '2018-01-28'
            INNER JOIN
        WORKLOAD WRK ON WRK.idLECTURE = TGFL.idLECTURE
            INNER JOIN
        TEACHER TEACH ON TEACH.idTEACHER = WRK.idTEACHER
            INNER JOIN
        CAT_TEACHER CAT ON CAT.idCAT_TEACHER = TEACH.idCAT
    GROUP BY LEC.idLECTURE , WRK.idTEACHER;CREATE OR REPLACE VIEW allpeople AS
    SELECT 
        COUNT(TGFL.idTRAININGFL) AS allpeople
    FROM
        TRAININGFL TGFL
    WHERE
        idCITY = 1
            AND TGFL.date_attestation BETWEEN '2018-01-01' AND '2018-01-28';SELECT 
    name,
    IFNULL(allin, 0) AS allin,
    IFNULL(hoursin, 0) AS hoursin,
    IFNULL(allout, 0) AS allout,
    IFNULL(hoursout, 0) AS hoursout,
    IFNULL(t1.people1, 0) AS people1in,
    IFNULL(t2.people1, 0) AS people1out,
    IFNULL(t1.people2, 0) AS people2in,
    IFNULL(t2.people2, 0) AS people2out,
    IFNULL(t1.people3, 0) AS people3in,
    IFNULL(t2.people3, 0) AS people3out,
    IFNULL(t1.people4, 0) AS people4in,
    IFNULL(t2.people4, 0) AS people4out,
    allpeople.allpeople
FROM
    tmp
        LEFT JOIN
    (SELECT 
        idTEACHER,
            SUM(IF(tmp.hours = 1, people, 0)) AS people1,
            SUM(IF(tmp.hours = 2, people, 0)) AS people2,
            SUM(IF(tmp.hours = 3, people, 0)) AS people3,
            SUM(IF(tmp.hours = 4, people, 0)) AS people4,
            COUNT(idLECTURE) AS allin,
            SUM(IF(tmp.hours > 0, hours, 0)) AS hoursin
    FROM
        tmp
    WHERE
        1 = 1 AND tmp.out = 1
    GROUP BY hours , idTEACHER
    ORDER BY name) AS t1 ON tmp.idTEACHER = t1.idTEACHER
        LEFT JOIN
    (SELECT 
        idTEACHER,
            SUM(IF(tmp.hours = 1, people, 0)) AS people1,
            SUM(IF(tmp.hours = 2, people, 0)) AS people2,
            SUM(IF(tmp.hours = 3, people, 0)) AS people3,
            SUM(IF(tmp.hours = 4, people, 0)) AS people4,
            COUNT(idLECTURE) AS allout,
            SUM(IF(tmp.hours > 0, hours, 0)) AS hoursout
    FROM
        tmp
    WHERE
        1 = 1 AND tmp.out = 0
    GROUP BY hours , idTEACHER
    ORDER BY name) AS t2 ON tmp.idTEACHER = t2.idTEACHER
        LEFT JOIN
    allpeople ON 1 = 1
GROUP BY tmp.idTEACHER
ORDER BY description , name

На Windows где собственно и пишу код с теми же самыми версиями пакетов все работает без геморроя.
Где то магия, где пока понять не могу :(

Ошибка при создании триггера в mysql

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

[IlluminateDatabaseQueryException]

SQLSTATE[42000]: Syntax error or access violation: 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 ‘END IF; END’ at line 4 (SQL:

        CREATE TRIGGER tr_Inser_Outer_Id_If_Null_to_Medobjects BEFORE INSERT ON peoples

        FOR EACH ROW BEGIN

            IF NEW.outer_id=NULL THEN

                SET NEW.outer_id=(SELECT max_num FROM (SELECT MAX(outer_id)+1 as max_num FROM `peoples`) AS t2)

            END IF;

        END

        )

[PDOException]

SQLSTATE[42000]: Syntax error or access violation: 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 ‘END IF; END’ at line 4

возникает из-за того, что операции в условиях

IF NEW.outer_id=NULL THEN

…;

…;

END IF;

должны заканчиваться «;»
Правильный код должен быть такой:

CREATE TRIGGER tr_Inser_Outer_Id_If_Null_to_Medobjects BEFORE INSERT ON `medobjects`

FOR EACH ROW BEGIN

    IF NEW.outer_id IS NULL THEN

        SET NEW.outer_id=(SELECT max_num FROM (SELECT MAX(outer_id)+1 as max_num FROM `medobjects`) AS t2);

    END IF;

END

  • Ошибка odbc sqlstate 42000 номер ошибки 102
  • Ошибка odbc sqlstate 28000 номер ошибки 18456
  • Ошибка odbc sqlstate 22018 номер ошибки 0
  • Ошибка odbc sqlstate 08004
  • Ошибка odbc sqlstate 08001 номер ошибки 101