0

I am getting a syntax error with the following PHP statement:

mysql_query("INSERT INTO table1 (to, from, msg, field, date)  
VALUES ('TEST_TO', 'TEST_FROM', 'TEST_MSG', 'TEST_FIELD', 'TEST_DATE')");

The returned error is:

You have an error in your SQL syntax.

What is the problem with the code?

CJ7
  • 22,579
  • 65
  • 193
  • 321

2 Answers2

6

to and from are reserved words. You need to quote them (with backticks since they are field names). (It is worth getting into the habit of always quoting field names rather then trying to remember which are reserved).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • also date is a reserved keyword – Abubakkar Oct 23 '12 at 06:17
  • 1
    @Abu — It is, but you don't need to quote it. It comes under the list on the page that I linked to that is prefixed: *MySQL permits some keywords to be used as unquoted identifiers because many people previously used them* – Quentin Oct 23 '12 at 06:18
3

You have reserved words in your column names like - from, to. Use backticks to escape.

  mysql_query("INSERT INTO table1 (`to`, `from`, `msg`, `field`, `date`)  
  VALUES ('TEST_TO', 'TEST_FROM', 'TEST_MSG', 'TEST_FIELD', 'TEST_DATE')");

Note: mysql_query is deprecated. Use mysqli_query or PDO functions.

janenz00
  • 3,315
  • 5
  • 28
  • 37