Search code examples
phpmysqlsqlmysql-error-1064

Simple 'SELECT field FROM table_name where TO = "$to"' is returning MySQL error 1064


This problem has got me stumped for a few days now.

I have a MySQL table that looks like this:

+--------+------------+------------+-----------+-----------+-----------+
|   id   |   to       |  from      |question   | answer    |  time     |
+--------+------------+------------+-----------+-----------+-----------+
|        |            |            |           |           |           |
| type:  |type:       |type:       |type:      |type:      | type:     |
| int(11)|varchar(26) |varchar(26) |tinyint(3) |tinyint(3) | bigint(20)|
|        |            |            |           |           |           |
|        |            |            |           |           |           |

I am trying to run a simple SELECT but I receive an error. This is the code I am using to run the query:

$to = mysql_real_escape_string($_POST['to']);
$query = "SELECT to FROM table_name WHERE to = '$to'";
$result = mysql_query("$query") or die(mysql_error() ."|". mysql_errno());

When I try to run this, this is what I am returned with:

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 'to FROM table_name WHERE to = 'userOne'' at line 1 | 1064

The 1064 at the end is the MySQL error number that is error is associated with. Error 1064 is some sort of parse error (Source: http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html#error_er_parse_error) But I am not sure what is causing this error. Also note the error is saying there is an error on line 1 but this line is actually line 68 in my code. I am able to run queries similar to SELECT * FROM other_table where name = "$name" on other tables in my database.

Any ideas why this query wont run properly?


Solution

  • The error is raised because the word to is reserved in mysql as you can read here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

    Thus, you should change this line:

    $query = "SELECT to FROM table_name WHERE to = '$to'";
    

    into this:

    $query = "SELECT `to` FROM table_name WHERE `to` = '$to'";