我已经尝试完成这项工作,但它会将所有行加起来,而不仅仅是像我在查询中尝试的那样 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;
?>
最佳答案
如果你没有绑定(bind)限制,那么改变你的查询
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
}
关于php - PDO 不调用一行的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26038070/