Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - WHERE, AND & OR syntax

Tags:

php

mysql

chat

I am programming a private chat thing, but now I get this problem:
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='gskartwii' OR sender='gskartwii' AND to='gs'' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\rivase\private.php on line 38
This is my code:

<!-- language: php -->
<?php
$result=mysql_query("SELECT * FROM rivase_chat_posts WHERE sender='$user' AND to='$user2' OR sender='$user2' AND to='$user'");
echo mysql_error();
while ($row = mysql_fetch_assoc($result)) {
    $sender=$row['sender'];
    $content=$row['content'];
    $time=$row['time'];
    echo "$sender : $content <span class='hidden'>$time</span><br />\n";
}
?>

Thanks for you all for the quick and good replies!

like image 947
gskartwii Avatar asked Dec 20 '22 16:12

gskartwii


2 Answers

try escaping to with backticks

$result=mysql_query("SELECT * FROM rivase_chat_posts 
                    WHERE sender='$user' AND `to`='$user2' 
                    OR sender='$user2' AND `to`='$user'");

since it is a reserved word in MySQL

like image 54
juergen d Avatar answered Jan 02 '23 22:01

juergen d


TO is a reserved word.

$result=mysql_query("SELECT * FROM rivase_chat_posts WHERE sender='$user' AND `to`='$user2' OR sender='$user2' AND `to`='$user'");

Should work.

like image 29
Wayne Whitty Avatar answered Jan 02 '23 20:01

Wayne Whitty