There have been a few threads lately which have had pdo queries or prepared statements within loops, which is obviously a silly idea and makes no sense. Prepare outside the loop, then execute within the loop.
However, I have a script where I am preparing a statement within a while loop, to be executed later in further conditions within the loop. I know it’s wrong, but don’t know how to prepare it before the loop in this case.
I think it’s some confusion on my part about what can/cannot be put in a prepared statement as a blind or named param.
It is a query that has a WHERE IN clause and comma separated list which will alter for each loop of the while. The end result looking something like this:-
"SELECT id, Name, Email FROM People WHERE id IN ('1, 3, 6, 10')"
To put this in more context, the script is part of a task management system. This is a small part of the code:-
$sql = $db->query("SELECT * FROM TaskList WHERE Notifcation != '4' AND Status != 'c' ");
while($row = $sql->fetch()){
$assigned = unserialize ($row['AssignedTo']); // Array of people assigned (IDs)
// also get other task info... not relevant here
$alist = implode("', '", $assigned) ; // create CSV of assigned people's IDs
$qstr = "SELECT id, Name, Email FROM People WHERE id IN ('".$alist."')" ; // create query string
$sqlass = $db->prepare($qstr); // prepare the statement
// A load more script that uses this to do stuff
} // end while
It seems I can’t set the CSV part, (the only bit that will change) as a param outside of the while loop, then define it’s value within the loop, as I would prefer to do. When I tried, it does not work.
Is it possible? If so, how?