0

I am working on a social networking site for my company and I am setting up the messaging system.

I have a table in the database called "mail" and for some reason the simplest SELECT query is returning an error. here's the code:

    $sql = "SELECT * FROM mail WHERE to='$username'";
$result = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_assoc($result)){
    $from = $row['from'];
    $content = $row['content'];
    echo "<tr><td>$from</td><td>$content</td></tr>";
}

It is returning this error; 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='cody'' at line 1

I have used this type of query with the same syntax a hundred times before I have no idea whats wrong this time.

A few notes: The database connection works fine, "to", "from" and "content" are columns in my "mail" table.

Thanks in advance for your help

2
  • Sounds like there might be a problem with the value of $username - or maybe in PHP you're supposed to use ` instead of ' for this sort of thing (I forget)? Commented Jun 1, 2011 at 17:37
  • can I recommend that you switch to prepared queries now, while you're early in development? I'd rather your site not get taken down by SQL injection attacks. Commented Jun 2, 2011 at 14:39

3 Answers 3

8

TO is a reserved word. Try the following instead

$sql = "SELECT * FROM mail WHERE `to`='$username'";

Reserved words are permitted as identifiers if you quote them as described in Section 8.2,

Reference

Sign up to request clarification or add additional context in comments.

1 Comment

+1, also please please please use prepared queries. People will start making usernames you don't like (' OR ''=')
0

"TO" is also a keyword try encapsulating the field name with a backtick `

Comments

0

I think the problem occurs due to this

to='$username'

$username is a Php variable so check out

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.