PDO not calling line order

I tried to make this work, but it adds all rows not only 5 as I am trying 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 issue of not being able to call the last 5 lines, I cannot validate the order line.

I've read questions similar to this on stackoverflow but still can't figure out how to get it right. maybe there are other problems with my code, but I can always add that if requsted :)

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;

?>

      

+3
php mysql pdo


source to share


1 answer


if you are not a mandatory 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
}

      

+3


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics