php - 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 !!
解决方案
不仅对于 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
, 的...
部分是参数解包操作符。
推荐阅读
- gstreamer - 如何使用 gstreamer 播放原始数据?
- reactjs - 赛普拉斯拖放“反应可排序树”元素
- swift - 通过 Parse Server 设置条形码扫描仪数据库:Swift
- python - 查找具有最多重叠项目的列表
- angularjs - 我如何忽略/修复 Raven 扫描 npm 库依赖项的漏洞
- bots - 如何对默认部分做出类似于 Dilos 流程中的信使的快速响应
- .net - 管理类库的用户机密
- python - Python:列表中每个月的最大日期
- r - 创建后更改 ggplot2 对象的点大小
- c++ - 在获取 DLL_PROCESS_DETACH 之前需要通知 DLL 正在关闭