Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda