问题
I am reading this answer: PHP - Using PDO with IN clause array
It uses the code:
$in_array = array(1, 2, 3);
$in = str_repeat('?,', count($in_array) - 1) . '?';
$sql = "SELECT * FROM my_table WHERE my_value IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($in_array);
$data = $stm->fetchAll();
Can anyone explain why they used
$in = str_repeat('?,', count($in_array) - 1) . '?';
instead off:
$in = str_repeat('?,', count($in_array));
I am puzzled and cannot figure out the logic behind the trailing - 1) . '?'
回答1:
This is because str_repeat() function repeats a string a specified number of times and count() function will return the length of the array which means that it will result in "?,?,?,?,?," if the array length is 5(let suppose) which doesn't looks formatted that's why count($in_array)-1 with '?' appended had been used.
来源:https://stackoverflow.com/questions/37713592/explanation-of-pdo-in-clause-using-prepared-statements