PHP PDO statement throwing fatal error
I have a function which is throwing an unusual error regarding a syntax issue. Have a look.
public static function authenticate($_user, $_pass)
{
$sql = 'SELECT password, key
FROM users
WHERE username = ' . $_user;
$stm = Db::init()->prepare($sql);
if ($stm->execute())
return $stm->fetch(PDO::FETCH_ASSOC);
}
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to 开发者_Go百科use near 'key FROM users WHERE username = testuser1' at line 1' in /class.php:111
Stack trace:
#0 /class.php(111): PDOStatement->execute() #1 /class.php(118): Password::authenticate('testuser1', 'test') #2 {main} thrown in /class.php on line 111
Any ideas as to what this means?
key
is a reserved word in sql. Surround it with backticks in your query. Like this:
public static function authenticate($_user, $_pass)
{
$sql = 'SELECT password, `key`
FROM users
WHERE username = ' . $_user;
$stm = Db::init()->prepare($sql);
if ($stm->execute())
return $stm->fetch(PDO::FETCH_ASSOC);
}
BTW: You have a SQL injection vulnerability in your code. Use a parameterized query to bind the value of $_user
.
精彩评论