首页 > 解决方案 > PHP SQL select 仅使用 IN 语句中数组的第一个结果

问题描述

我正在尝试根据从我放入数组的表中选择的 ID 对列求和。出于某种原因,在 Where 子句中只使用了第一个 ID。当我回显变量时,所有的 id 都在那里。我究竟做错了什么?

$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT 
    id 
    FROM account
    WHERE  level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
    $stmt3->bind_param("ss",$usernamesession,$groupname);
    $stmt3->execute();
    $result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
    

    while ($rowid = $result3->fetch_assoc())
{
    $counttheid[] = $rowid['id'];
    $countid = implode(',', $counttheid); // contains all the ids !!


}

$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)  
     ";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("i",$countid);
    $stmt->execute();
    $stmt->bind_result($row['totalcash']);
    while($stmt->fetch()) $sumcash = $row['totalcash'];

    echo $sumcash; // Somhow only the sum of the first ID of the array !!
    
    echo $countid;// all the ids from the array !!

标签: phparraysmysqli

解决方案


不仅对于 in,而且绑定参数的数量也需要匹配。

尝试使用此示例获取从while到的代码execute

while ($rowid = $result3->fetch_assoc())
{
    $counttheid[] = $rowid['id'];
    // $countid = implode(',', $counttheid); // contains all the ids !!
}

$in = str_repeat('?,', count($counttheid) - 1) . '?';
$types = str_repeat('i', count($counttheid));
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN ($in)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$counttheid);
$stmt->execute();

bind_param, 带有...$counttheid, 的...部分是参数解包操作符


推荐阅读