$myArray = array(1,2,3); $in = trim(str_repeat('?,', count($myArray)),','); $stm = $conn->prepare("SELECT * FROM table WHERE id IN ($in)"); $stm->execute($myArray);萬一遇上 $myArray 的個數很多時,會造成語法太長,無法執行怎麼辦?
試試下面這個方法
$myArray = array(1,2,3); $in = implode(',', $myArray); $stm = $conn->prepare("SELECT * FROM table WHERE FIND_IN_SET(id, :inArray) ORDER BY name"); $stm->bindParam('inArray', $in); $stm->execute();如果是 not in,就加上一驚嘆號,變成 !FIND_IN_SET 就可以了
$myArray = array(1,2,3); $in = implode(',', $myArray); $stm = $conn->prepare("SELECT * FROM table WHERE !FIND_IN_SET(id, :inArray) ORDER BY name"); $stm->bindParam('inArray', $in); $stm->execute();
沒有留言:
張貼留言