2

I'm getting this error displayed on my screen I have been trying to debug.

"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 = 'testname'' at line 1"

my function im using for this is as follows:

function recentMessages() {
    $tbl_name="messages";
    $username = $_SESSION['username'];
    $result = mysql_query("SELECT * FROM $tbl_name WHERE to = '$username' ") or die(mysql_error());
    while ($row = mysql_fetch_row($result))
      {
        return $row['date']." ".$row['time']." ".$row['from']." ".$row['subject']. "<br />";    
      }
}

Basically what im trying to do is to get all the rows of data from the database messages where who its 'to' is the username of the session and its echo'd out. Any ideas on what im doing wrong? thanks

Nexus9988
  • 79
  • 1
  • 11
  • @BrendanLong it's a valid point (of course) to escape variables in sql but: if it's trivial to modify session data, sql injection would be the least of your application's worries. Andrew - consider having $username = "' OR 1=1 or x='" – AD7six Oct 23 '12 at 21:34
  • You should really [escape string data](http://php.net/manual/en/function.mysql-real-escape-string.php) from external sources before using it in the database, even if you think it is probably safe. – Brendan Long Oct 23 '12 at 21:37

4 Answers4

10

to is a reserved word. Encase it in tick marks.

... WHERE `to` = '$username'

See the MySQL reserved words.

You should avoid using reserved words if possible.

Kermit
  • 33,827
  • 13
  • 85
  • 121
1

The to is a reserved word. Try this:

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

In general try to avoid small words like to, between, from ... e.t.c. just to prevent this kind of issues. A better solution is to have a field name like : "receiver" or "message_to" or something similar

John Skoumbourdis
  • 3,041
  • 28
  • 34
0

TO is Reserved Words in MySQL. Use backticks to Separates that.

SELECT * FROM $tbl_name WHERE `to` = '$username'
Rush
  • 740
  • 4
  • 13
-1

to is a reserved word I believe. Try changing to to [to] Edit: Wasn't sure entirely. I put it in SQL Server and saw that TO was a reserved word.

sjramsay
  • 555
  • 1
  • 5
  • 12