From 9d85d6e1851fd9fa3387919e338918c7cfe8ca2c 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:07:37 +0000 Subject: [PATCH] Optimize admin question view to fix N+1 query issue Refactored the question fetching logic in `admin.php` to use eager loading for answers. Instead of executing a separate query for each question to fetch its answers, we now fetch all questions first, collect their IDs, and execute a single query to fetch all relevant answers. This reduces the query count from N+1 (where N is the number of questions) to 2. Benchmark results (using SQLite proxy): Baseline: ~0.34s (1000 questions) Optimized: ~0.01s (1000 questions) Improvement: ~27x faster execution for data fetching logic. Co-authored-by: xRahul <1639945+xRahul@users.noreply.github.com> --- quiz_system_git/admin.php | 46 +++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/quiz_system_git/admin.php b/quiz_system_git/admin.php index 25b2532..faf4140 100755 --- a/quiz_system_git/admin.php +++ b/quiz_system_git/admin.php @@ -986,9 +986,28 @@ $stmt->execute(['quizID' => $get_quiz_id]); } + $all_questions = $stmt->fetchAll(); + + // Gather all question IDs + $question_ids = []; + foreach ($all_questions as $q) { + $question_ids[] = $q['question_id']; + } + + // Fetch all answers in one go + $answers_map = []; + if (!empty($question_ids)) { + $placeholders = implode(',', array_fill(0, count($question_ids), '?')); + $stmtAns = $pdo->prepare("SELECT * FROM answers WHERE question_id IN ($placeholders)"); + $stmtAns->execute($question_ids); + while ($row = $stmtAns->fetch()) { + $answers_map[$row['question_id']][] = $row; + } + } + $m_display_ID = 1; - while($m_row = $stmt->fetch()){ + foreach($all_questions as $m_row){ $m_answers=''; //id var = id column and so on $m_id = $m_row['id']; @@ -1031,25 +1050,24 @@ } //gathering answers of question here - $stmtAns = $pdo->prepare("SELECT * FROM answers WHERE question_id=:questionID"); - $stmtAns->execute(['questionID' => $m_question_id]); - $m_answers .= '
    '; - while($m_row2 = $stmtAns->fetch()){ - //putting column values in variables - $m_answer = $m_row2['answer']; - $m_correct = $m_row2['correct']; - - if($m_correct == 1) - $m_answers .= ''; - $m_answers .= '
  1. '.$m_answer.'
  2. '; - if($m_correct == 1) - $m_answers .= '
    '; + if (isset($answers_map[$m_question_id])) { + foreach($answers_map[$m_question_id] as $m_row2){ + //putting column values in variables + $m_answer = $m_row2['answer']; + $m_correct = $m_row2['correct']; + + if($m_correct == 1) + $m_answers .= ''; + $m_answers .= '
  3. '.$m_answer.'
  4. '; + if($m_correct == 1) + $m_answers .= '
    '; + } } $m_answers .= '