From 21b778bd7fbe86d4a55f8de0f9b1d1b1260091cf Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Tue, 27 Jan 2026 18:14:25 +0000 Subject: [PATCH] Optimize answer randomization in quiz.php Replaced inefficient `ORDER BY rand()` with application-layer shuffling in PHP. Refactored question and answer fetching to use `fetchAll()` instead of `fetch()` loops. This improves performance by avoiding filesort operations in the database and also fixes potential issues with nested queries and unbuffered result sets. Updated row checks to use `count()` on fetched arrays instead of unreliable `rowCount()` for SELECT queries (improving SQLite compatibility for testing). Co-authored-by: xRahul <1639945+xRahul@users.noreply.github.com> --- quiz_system_git/quiz.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/quiz_system_git/quiz.php b/quiz_system_git/quiz.php index ff17aec..eacc3e2 100644 --- a/quiz_system_git/quiz.php +++ b/quiz_system_git/quiz.php @@ -31,9 +31,10 @@ //checking if user has already taken this quiz $stmtCheck = $pdo->prepare("SELECT id FROM quiz_takers WHERE username = :username AND quiz_id=:quizID"); $stmtCheck->execute(['username' => $roll_no, 'quizID' => $final_quiz_ID]); + $taken = $stmtCheck->fetch(); //if user already did, redirect to index.php with error - if($stmtCheck->rowCount() > 0){ + if($taken){ $user_msg = 'Sorry, but '.$roll_no.', has already attempted the quiz, '.$quzz_name.'!'; header('location: index.php?user_msg='.urlencode($user_msg)); exit(); @@ -72,8 +73,9 @@ $stmtQ->bindValue(':quizID', $final_quiz_ID); $stmtQ->bindValue(':limit', $total_questions, PDO::PARAM_INT); $stmtQ->execute(); + $questions = $stmtQ->fetchAll(); - if ($stmtQ->rowCount() < 1) { + if (count($questions) < 1) { $user_msg = 'Hey, weird, but it seems there are no questions in this quiz!'; header('location: index.php?user_msg='.urlencode($user_msg)); exit(); @@ -83,7 +85,7 @@ $m_display_ID = 1; //looping through the questions and adding them on the page - while($m_row = $stmtQ->fetch()){ + foreach($questions as $m_row){ //initializing the options $m_answers=''; @@ -116,15 +118,17 @@ } //gathering options of the question here - $stmtAns = $pdo->prepare("SELECT * FROM answers WHERE question_id=:questionID ORDER BY rand()"); + $stmtAns = $pdo->prepare("SELECT * FROM answers WHERE question_id=:questionID"); $stmtAns->execute(['questionID' => $m_question_id]); + $answers = $stmtAns->fetchAll(); + shuffle($answers); $m_answers .= '