Added ml.id to all the three queries to fix array indexing problem when getting data using $DB->get_records_sql()