简体   繁体   English

PDO没有调用行的顺序

[英]PDO not calling the order of a row

I have tried to make this work but it adds up all the rows not just 5 like I am trying to in the query 我试图使这项工作,但它加起来所有的行,而不是像我在查询中尝试的那样

$username = $_SESSION['username'];
$stmt = $db->prepare("
select sum(correct) from exams where 
username = :username ORDER BY :testID DESC LIMIT :5");

Due to the problems with not being able to callthe last 5 rows I am unable to test the ordering string. 由于无法调用最后5行的问题,我无法测试排序字符串。

I have read questions similar to this on stackoverflow but still cant seem to get it right. 我已经在stackoverflow上阅读了与此类似的问题,但似乎仍然无法做到正确。 maybe there are other problems with my code but I can always add that if requsted :) 也许我的代码还有其他问题但我总是可以添加,如果需要:)

the full code 完整的代码

   <?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;

?>

if you are not binding limit then change your query 如果您没有约束限制,则更改您的查询

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)'];
 }

to

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM