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?

5
  • You are using an obsolete database API
    – Quentin
    Oct 23, 2012 at 6:15
  • @Quentin: what is the recommended replacement?
    – CJ7
    Oct 23, 2012 at 6:17
  • Follow the links through to php.net/manual/en/mysqlinfo.api.choosing.php
    – Quentin
    Oct 23, 2012 at 6:17
  • @Quentin: when will mysql_query functions no longer work on most servers?
    – CJ7
    Oct 23, 2012 at 6:26
  • A timeline hasn't been announced. mysql_* still doesn't support paramterized queries though, and they are the best defence against SQL Injection attacks.
    – Quentin
    Oct 23, 2012 at 6:27

2 Answers 2

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).

2
  • also date is a reserved keyword
    – Abubakkar
    Oct 23, 2012 at 6: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, 2012 at 6: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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.