我已经尝试过让它工作,但它将所有行相加,而不是像我在查询中尝试的那样只加5行
$username = $_SESSION['username'];
$stmt = $db->prepare("
select sum(correct) from exams where
username = :username ORDER BY :testID DESC LIMIT :5");
由于无法调用最后5行的问题,我无法测试排序字符串。
我在stackoverflow上读到过类似的问题,但似乎仍然无法正确回答。也许我的代码还有其他问题,但如果需要,我可以随时添加:)
全代码
<?php
require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
$username = $_SESSION['username'];
$last5rate = $db->prepare("select sum(correct) from exams where username = :username ORDER BY :testID DESC LIMIT 5");
$last5rate->execute(array(':username' => $username));
for($i=0; $rows = $last5rate->fetch(); $i++){
//Edit this row
$last5 = $rows['sum(correct)'];
$last5final = $last5 / 10;
}
echo $last5final;
?>
如果您没有绑定限制,则更改您的查询
select sum(correct) from exams where username = :username ORDER BY :testID DESC LIMIT :5
$last5rate->execute(array(':username' => "$username"));
for($i=0; $rows = $last5rate->fetch(); $i++){
$last5 = $rows['sum(correct)'];
}
至
select sum(correct) as correct from exams where username = :username ORDER BY :testID DESC LIMIT 5
$last5rate->execute(array(':username' => $username,':testID' => $testID));
while ($row = $last5rate->fetch(PDO::FETCH_ASSOC)) {
echo $row['correct']; // or use it as you want
}