因此,此sql旨在从projects表中返回1个随机项目
$sql = "select title, id, user_id, priority from projects
where ( closed = 0 and priority between 7 and 9 AND user_id=$user_id )
ORDER by rand(), priority
limit 1";
无论我如何用括号等对它们进行重新排列,查询都将返回无效错误,例如
Notice: Undefined variable: user_id in /var/www/html/producerswip/includes/functions.php on line 734
Fatal error: Uncaught PDOException: 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 use near ') ORDER by rand(), priority limit 1' at line 2 in /var/www/html/producerswip/includes/functions.php:737 Stack trace: #0 /var/www/html/producerswip/includes/functions.php(737): PDO->prepare('select title, i...') #1 /var/www/html/producerswip/index.php(72): getRandomProject() #2 {main} thrown in /var/www/html/producerswip/includes/functions.php on line 737
更新 这是全脸掌心的时刻。我非常关注sql语句错误,因此忽略了第一行,它实际上指出了错误。感谢@David和其他睁开眼睛的人。我也接受了@David的建议,并将我的sql更改为以下内容,这对sql注入没有吸引力
$sql = "select title, id, user_id, priority from projects
where ( closed = ? and priority between ? and ? AND user_id=? )
ORDER by rand(), priority
limit 1";
$results = $pdo->prepare($sql) or die(mysqli_error($pdo));
$results->execute([0,7,9,$user_id]);
答案 0 :(得分:1)
看起来您的$user_id
变量未定义,这意味着您生成的查询将变为以下内容:
where ( closed = 0 and priority between 7 and 9 AND user_id= )
ORDER by rand(), priority
limit 1
由于user_id=
后没有值,因此查询无效。