So this sql is designed to return 1 random project from the projects table
$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";
No matter how I rearrange them with parenthesis etc. the query returns invalid error like
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
UPDATE This is a total face palm moment. I was so focused on the sql statement error I ignored the first line which actually states the error. Thanks @David and others who have their eyes open. I have also taken @David advice and changed my sql to the following which is less attractive to sql injection
$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]);