PDO bind array to Where IN

后端 未结 4 1619
执念已碎
执念已碎 2021-01-23 18:29

I want to bind a array of Strings to the WHERE IN part of a SQL command, which I want to run afterwards on a SQL Server. The problem is probably that I try to bind

4条回答
  •  温柔的废话
    2021-01-23 19:00

    Here is the snippet I use when trying to achieve an IN statement with an array.

    This works dynamically, so whether you have an array of 2 or 200 it should execute as expected.

    $ids = array(1,2,3);
    $in  = str_repeat('?,', count($ids) - 1) . '?';
    $sql = "SELECT * FROM table WHERE column IN ($in)";
    $stm = $db->prepare($sql);
    $stm->execute($ids);
    $data = $stm->fetchAll();
    

    Your code will look like so:

    $refIdsPartial = array('54469c27c687b332339627','54469ba0dec3e703865612','54469c77945c7091266617');
    $in  = str_repeat('?,', count($refIdsPartial ) - 1) . '?';
    $totalCount = "SELECT referral, COUNT(username) AS cnt FROM accounts WHERE referral IN ($in) GROUP BY referral";
    $ps_totalCounts = $dbh->prepare($totalCount);
    $ps_totalCounts->execute();
    
    //loop over total counts
    foreach($ps_totalCounts as $row)
    {
        echo "Test
    "; }

提交回复
热议问题