From 72e9a1bbd94361910bd557d5e1e86eff52691111 Mon Sep 17 00:00:00 2001 From: Mihail Geshoski Date: Tue, 9 Apr 2024 00:34:39 +0800 Subject: [PATCH] MDL-81458 question: Cast the fraction value to a float When retrieving the answer data from the database, it's essential to cast the value of the answer's fraction to a float before storing it into the question object. This step is crucial for ensuring consistency, as some database engines return floats as strings like '1.0000000'. --- question/type/questiontypebase.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/question/type/questiontypebase.php b/question/type/questiontypebase.php index 3f9130fba43..78f585d7f4d 100644 --- a/question/type/questiontypebase.php +++ b/question/type/questiontypebase.php @@ -931,13 +931,13 @@ class question_type { if (is_array($extraanswerfields)) { $answerextensiontable = array_shift($extraanswerfields); // Use LEFT JOIN in case not every answer has extra data. - $question->options->answers = $DB->get_records_sql(" + $answers = $DB->get_records_sql(" SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . ' FROM {question_answers} qa ' . " LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid WHERE qa.question = ? ORDER BY qa.id", array($question->id)); - if (!$question->options->answers) { + if (!$answers) { echo $OUTPUT->notification('Failed to load question answers from the table ' . $answerextensiontable . 'for questionid ' . $question->id); return false; @@ -945,9 +945,15 @@ class question_type { } else { // Don't check for success or failure because some question types do // not use the answers table. - $question->options->answers = $DB->get_records('question_answers', + $answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC'); } + // Store the answers into the question object. + $question->options->answers = array_map(function($answer) { + // Some database engines return floats as strings like '1.0000000'. Cast to float for consistency. + $answer->fraction = (float) $answer->fraction; + return $answer; + }, $answers); $question->hints = $DB->get_records('question_hints', array('questionid' => $question->id), 'id ASC');