Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Moodle Complex SQL not working

I'm writing a block in PHP for Moodle 3.2 and I'm having a little difficulty with the SQL not working.

Basically I want to get the quiz scores for all users on a course for all the quizzes.

My SQL works in phpMyAdmin

SELECT u.id, u.firstname, u.lastname, qg.quiz, qg.grade, 
     q.grade as maxgrade, q.name 
FROM mdl_quiz_grades qg 
JOIN mdl_user u ON u.id = qg.userid 
JOIN mdl_quiz q ON q.id = qg.quiz 
WHERE q.course = 2 

As I say this working in MySQL: enter image description here

However here is the PHP code in Moodle:

$sql = "
SELECT  u.id, u.firstname, u.lastname, 
        qg.quiz, qg.grade, q.grade AS maxgrade, q.name 
FROM {quiz_grades} qg 
JOIN {user} u ON u.id = qg.userid 
JOIN {quiz} q ON q.id = qg.quiz 

WHERE q.course = ?"; 
$params = array($COURSE->id);**//NB Course ID is 2**
$records = $DB->get_records_sql($sql, $params);
print_r($records);

Which produces only the two records where the QUIZ id is also 2.

Array ( [5] => stdClass Object ( [id] => 5 [firstname] => Bart [lastname] => Simpson [quiz] => 2 [grade] => 5.00000 [maxgrade] => 10.00000 [name] => Quiz 2 ) [6] => stdClass Object ( [id] => 6 [firstname] => Lisa [lastname] => Simpson [quiz] => 2 [grade] => 5.00000 [maxgrade] => 10.00000 [name] => Quiz 2 ) )

I'm unclear where I have gone wrong but also why I get two different results

Any advice cheerfully received,

Many Thanks

Dave

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

When you use any of the Moodle $DB->get_records* functions, the results are returned as an array, indexed by the first field retrieved.

So, in this case, the array will be indexed by the userid - so there will only be 2 records, as there are only 2 different user ids.

If you want to use $DB->get_records* functions, you will have to ensure the first field is something unique (e.g. 'qg.id').

Alternatively, you can use $DB->get_recordset_sql(), which will then let you iterate through the results, without worrying about duplicate ids.

Before you write any more Moodle code, please turn on developer debugging, as that would have given you a warning message in this situation.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!