PDA

View Full Version : mysql query


dladenhe
06-17-2008, 06:11 PM
Hey,

I am making a registration page with PHP and mySQL, and I'm having an error which I cannot solve. At this point, I am trying to check if the username already exists in the database. This is the 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 ''users' WHERE 'username'='admin'' at line 1

Here is the code:

$sql = "SELECT * FROM 'users' WHERE 'username'='$username'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "this username already exists"; }

Does it have to do with my version of mySQL? I have version 5.0.24a

THANKS FOR YOUR HELP

Iszak
06-17-2008, 07:11 PM
It tends to be because you've got both the column and the value in the same quotes try replacing it with


"SELECT * FROM `users` WHERE `username`='admin'"


it should work, if it does thank me.

dladenhe
06-17-2008, 09:09 PM
but since its a registration it needs to be a variable because it will not always be admin logging in. does that make sense? if you cant have a column and value in the same quotes, how would i perform this check?

ok anyway i got it to work by using this syntax:

"SELECT username FROM users WHERE username='$username' ";

However, I still don't understand WHY this worked. can anyone explain please?

Iszak
06-17-2008, 10:05 PM
because you haven't got the 'username' column in the quotes that is the same to the username column value. Just like my example It's using both ` and ' instead of both using '. So in the case of variable you can use this.


"SELECT * FROM `users` WHERE `username`='{$username}'"