【发布时间】:2021-05-24 06:07:07
【问题描述】:
我正在尝试根据从我放入数组的表中选择的 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 子句中的每个值都需要有一个
?。见this pdo IN clause example 概念是一样的。 -
嗯好的。比如何在 where 子句中使用数组?
-
试过这样。它不起作用..
$in = str_repeat('?,', count($countid) - 1) . '?';SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (".$in.")