我想按用户ID
计算值列例如:我想计算标记列中id = 1的值 意味着(30 + 70 + 30)在获取sql代码中的用户标记后如何做到这一点
数据库示例
id mark user_id
----- ---- --------
1 30 1
2 60 3
3 70 1
4 10 2
5 30 1
我的代码
<?php
$mark = $DB_con->prepare("SELECT id,mark,user_id FROM `tablename` WHER user_id=".$userRow['id']."");
$mark->execute();
foreach($mark->fetchAll() as $mar){
echo count($mar['mark']);
}
?>
答案 0 :(得分:1)
为什么不喜欢
$mark = $DB_con->prepare("
SELECT sum(mark)
FROM `tablename`
WHERE user_id = ?");
$mark->bindParam(1, $userrow['id'], PDO::PARAM_INT);
顺便说一下,如果你从客户端获取那个用户ID,你可能应该使用bindParam,这样你就不会受到sql注入的攻击。</ p>
答案 1 :(得分:0)
也许是这样的事情;
<?php
$mark = $DB_con->prepare("SELECT id, mark, user_id FROM `tablename` WHERE user_id=$userRow['id']");
$mark->execute();
$total = 0;
foreach($mark->fetchAll() as $mar){
$total += $mar['mark'];
}
echo $total;
?>
答案 2 :(得分:0)
<?php
$mark = $DB_con->prepare("SELECT id,mark,user_id FROM `tablename` WHER user_id=".$userRow['id']."");
$mark->execute();
$counter = 0; // <-- THIS -----------
foreach($mark->fetchAll() as $mar){
echo count($mar['mark']);
$counter += $mar['mark']; // <-- THIS ----------
}
echo $counter;
?>
*还错过了&#39; WHERE&#39;在上面的陈述中。