Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Limit getting ignored

Tags:

php

sql-limit

pdo

I have this code and its calculating all the rows in the column correct and igonring the LIMIT 5

The line of code thats getting ignored


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

here is the whole 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;

?>

I have tried the following methods


select sum(correct) from exams where username 
= :username ORDER BY testID DESC LIMIT 0,5

AND

select sum(correct) from exams where username 
    = :username ORDER BY testID DESC LIMIT 5

like image 477
thenashone Avatar asked Mar 29 '26 23:03

thenashone


1 Answers

LIMIT limits the amount of results it returns

Your SUM always returns 1 result, so your limit will not do anything.

You might need something like this (untested, just for example)

SELECT sum(correct) FROM(
    select correct from exams where username 
    = :username DESC LIMIT 5
)

I removed the order, fiddle with it as needed.

like image 168
Nanne Avatar answered Apr 02 '26 05:04

Nanne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!