Using bind_param
on all my queries, I now want to use an IN(?)
where the number of elements in the list can vary.
The SQLout function I'm using here basically does a $sql_db->prepare
, ->bind_param
, ->execute()
, ->store_result()
, ->bind_result
// the code below does not work as the query only matches on element 'a':
$locations = ('a','b','c','d','e');
SQLout ("SELECT Name FROM Users WHERE Locations IN (?)",
array('s', $locations), array(&$usrName));
// the code below does work as a brute-force method,
// but is not a viable solution as I can't anticipate the number of elements in $locations going forward:
SQLout ("SELECT Name FROM Users WHERE Locations IN (?,?,?,?,?)",
array('sssss', $locations[0],$locations[1],$locations[2],$locations[3],$locations[4]), array(&$usrName));
Has anyone come up with a more elegant solution to this?
Best Answer
This is one place placeholders fall on their faces. Minus the auto-escaping, they're almost literally just a string replacement operation internally, meaning that if you have
WHERE Locations IN (?)
, and pass in1,2,3,4
, you'll get the equivalent oflogically equivalent to
instead of the intended
The only practical solution is to build your own list of comma-separated placeholders (
?
), e.g:and then bind your parameters are usual.