What is wrong with following mysql query
I'm writing a php scripts that selects a user from a mysql database. The user is defined by a username and a group where the user belongs to. I did this before but now I get an error.
function user($username, $group) {
$result = mysql_query("SELECT * FROM users
WHERE username='$username' AND group='$group'")
or die(mysql_error()); }
I'm running the script with xampp version: 1.7.4 with PHP version: 5.3.5 (VC6 X86 32bit) + PEAR and MySQL version 5.5.8 (Community Server). It get the following 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 'group='1a'' at line 1
I tried adding quotes around group and username, than I didn't get the error anymore but the query didn't find the row in the database while I'm sure it's th开发者_开发知识库ere.
group
is mysql reserved word
enclose column name in backticks
$result = mysql_query("SELECT * FROM users
WHERE `username`='$username'
AND `group`='$group'") or die(mysql_error());
Here is a list of mysql reserved words
It should have been
"SELECT * FROM `users` WHERE `username`='$username' AND `group`='$group'"
You have some major flaws in your code
you wrote all your code into a single line making it extremely hard to read and handle.
You don't properly escape your variables.
You don't have proper error handling
And a one minor one:
group
is a reserved word as it was mentioned already.
A code should be
function user($username, $group) {
$username = mysql_real_escape_string($username);
$group = mysql_real_escape_string($group);
$sql = "SELECT * FROM `users` WHERE `username`='$username' AND `group`='$group'";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// dunno what should be here, assuming a user data
return mysql_fetch_assoc($res);
}
精彩评论