我有一个foreach循环,它将在我的数据库中进行搜索。我想获得搜索返回的总行数。
目前,我有这个:
foreach ($stmt as $row) {
$search=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE username=:username AND token=:token");
$search->bindParam(":username",$userdata['id']);
$search->bindParam(":token",$row['token']);
$search->execute();
echo $search->rowCount();
}
这将打印出来:00001100
- 我怎样才能得到它们的总结果? (在这种情况下,它将是2)
更好的是,如何在foreach循环中获得 在 之外的总结果?
循环外的代码是:
$stmt = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='1' AND fixed_expire>:time AND membershipFilter='0'");
$stmt->bindParam(":time",time());
$stmt->execute();
$f=$stmt->rowCount();
答案 0 :(得分:2)
您可以执行以下操作 -
$count = 0 ;
foreach ($stmt as $row) {
$search=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE username=:username AND token=:token");
$search->bindParam(":username",$userdata['id']);
$search->bindParam(":token",$row['token']);
$search->execute();
$count += $search->rowCount();
}
echo $count ;
答案 1 :(得分:0)
通过像htis这样的变量来计算:
$total = 0;
foreach ($stmt as $row) {
$search=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE username=:username AND token=:token");
$search->bindParam(":username",$userdata['id']);
$search->bindParam(":token",$row['token']);
$search->execute();
$total += $search->rowCount();
}
$total
将保留总值。
答案 2 :(得分:0)
上述参与者都没有真正理解他们所写代码的含义:) 此外,rowCount永远不应该用于此目的,即使在这种特殊情况下数字不是那么高
$total = 0;
$query = "SELECT count(*) FROM advertisement_clicks
WHERE username=:username AND token=:token";
$search = $dbh->prepare($query);
$search->bindParam(":username", $userdata['id']);
$search->bindParam(":token", $row['token']);
foreach ($stmt as $row) {
$search->execute();
$total += $search->fetchColumn();
}
必须是
此外,假设$ stmt是先前查询的结果,大多数情况下您可以通过使用GROUP BY运算符获取其他查询中的计数。 没有这样的额外循环
答案 3 :(得分:-1)
$x = 0;
foreach ($stmt as $row) {
$search=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE username=:username AND token=:token");
$search->bindParam(":username",$userdata['id']);
$search->bindParam(":token",$row['token']);
$search->execute();
echo $search->rowCount();
$x++;
}
echo $x;