Explanation of PDO IN clause using prepared statements

我与影子孤独终老i 提交于 2021-02-11 15:21:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!