简体   繁体   中英

mysql SELECT query returning error with correct syntax

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

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

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

I think the problem occurs due to this

to='$username'

$username is a Php variable so check out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM