简体   繁体   中英

Join query in Moodle only returns last column only while mysql returns correctly

I have 2 tables in my moodle database such as equiz_details and equiz_responses as follows:

mdl_equiz_details:

在此处输入图片说明

mdl_equiz_details

在此处输入图片说明

I have used a join query to fetch result as desired form as follows:

SELECT distinct ed.quizid,ed.questionnumber,ed.questiontext,ed.optiontext1,ed.optiontext2,ed.optiontext3,ed.optiontext4, ed.correctanswer,er.studentanswer FROM `mdl_equiz_details` as ed INNER JOIN `mdl_equiz_responses` as er ON ed.quizid = er.quizid and ed.questionnumber = er.questionnumber and er.studentid=4 and er.quizid=25

I fired the query in mysql database annd got result as follows:

Result in mysql

在此处输入图片说明

I am using the same query inside my moodle page and try to fetch result as follows::

<?php
require_once('../../config.php');
global $DB; 

$quizresdetails = $DB->get_records_sql("SELECT ed.quizid,ed.questionnumber,ed.questiontext,ed.optiontext1,ed.optiontext2,ed.optiontext3,ed.optiontext4, ed.correctanswer,er.studentanswer FROM {equiz_details} ed INNER JOIN {equiz_responses} er ON ed.quizid = er.quizid and ed.questionnumber = er.questionnumber and er.studentid=4 and er.quizid=25");      

var_dump($quizresdetails);

?>

I am getting the result as follows:

Result in Moodle page

在此处输入图片说明

Which is obviously the last result.

What I am doing wrong? How can I fetch full result in my moodle page?

Moodle version: 2.9.1

The problem is your query is returning the same value for its id in each record: "25". The Moodle get_records_* methods expect every result to have a unique id, as it uses that id as the array key in the array of results it returns. So it's finding all your results, but as it loops through them it is adding each result to the array key "25", so then when it gets to the end, it only has the last result in the returned array.

So you need to return a field with a unique id for each row, as "id".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM