Moodle fetch Student Grades


To fetch student’s grade from Moodle database you can use this query


SELECT u.firstname AS `First Name` , u.lastname AS `Last Name` , AS Email, c.idnumber AS `Course Acronym` , c.fullname AS Course, ROUND( gg.finalgrade, 2 ) Grades, AS City, AS Country, FROM_UNIXTIME( gi.timemodified ) `Grading Date`
FROM mdl_course AS c
JOIN mdl_context AS ctx ON = ctx.instanceid
JOIN mdl_role_assignments AS ra ON ra.contextid =
JOIN mdl_user AS u ON = ra.userid
JOIN mdl_grade_grades AS gg ON gg.userid =
JOIN mdl_grade_items AS gi ON = gg.itemid
WHERE gi.courseid =
AND gi.itemtype = ‘course’
AND c.idnumber IN (‘C101’, ‘C102’, ‘C103’, ‘C104’, ‘C105’)

ORDER BY c.idnumber




Improve Moodle Performance

Hardware Configuration:

  • The fastest and most effective change to improve performance is to increase the amount of RAM on the web server – get as much as possible (e.g. 4GB or more). Increasing primary memory will reduce the need for processes to swap to disk and will enable your server to handle more users.
  • Better performance is gained by obtaining the best processor capability, i.e. dual or dual core processors.
  • We should use SCSI hard disks instead of SATA drives. SATA drives will increase the system’s CPU utilization, whereas SCSI drives have their own integrated processors and come into their own when we have multiple drives. If we already have SATA drives, check that the motherboard and the drives themselves support NCQ (Native Command Queuing).
  • Purchase hard disks with a low seek time. This will improve the overall speed of the system, especially when accessing Moodle’s reports.
  • Size the swap file correctly. The general advice is to set it to 4 x physical RAM.
  • Use a RAID disk system. Although there are many different RAID configurations we can create, the following generally works best:
    • Install a hardware RAID controller (if we can)
    • The operating system and swap drive on one set of disks configured as RAID-1.
    • Moodle, Web server and Database server on another set of disks configured as RAID-5.
  • We should use Gigabit Ethernet for improved latency and throughput. This is especially important when we have the webserver and database server separated out on different hosts.
  • Check the settings on the network card. We can get an improvement in performance by increasing the use of buffers and transmit/receive descriptors (balance this with processor and memory overheads) and off-loading TCP checksum calculation onto the card instead of the OS.

PHP Performance:

  • It is strongly recommended to use a PHP accelerator to ease CPU load, such as APCPHPAXcacheWinCache or eAccelerator.
  • Increasing the database connection lifetime, could be around session.gc_maxlifetime “14400”

Apache Performance:

  • Set the MaxClients directive correctly. Use this formula to help (which uses 80% of available memory to leave room for spare):

MaxClients = Total available memory * 80% / Max memory usage of apache process

  • Use the latest version of Apache – Apache 2 has an improved memory model which reduces memory usage further.
  • For Unix/Linux systems, consider lowering MaxRequestsPerChild in httpd.conf to as low as 20-30 (if you set it any lower the overhead of forking begins to outweigh the benefits).

MySQL Performance:

  • Enable the query cache with query_cache_type = 1
  • Set query_cache_size = 36M & query_cache_min_res_unit = 2K
  • Set the maximum number of connections may be around 200
  • Optimize database tables weekly and after upgrading Moodle. It is good practice to also optimize your tables after performing a large data deletion exercise, e.g. at the end of the academic session. This will ensure that index files are up to date. We should Backup our database first and then use:
  • mysql>CHECK TABLE mdl_tablename;
  • mysql>OPTIMIZE TABLE mdl_tablename

The common tables in Moodle to check are mdl_course_sections, mdl_forum_posts, mdl_log and mdl_sessions. Any errors need to be corrected using REPAIR TABLE.

Thanks to


Moodle Error: List of all users shows a fatal error message {Fatal error: Call to undefined method MoodleQuickForm_hidden::MoodleQuickForm_hidden() in …


If you every face this error List of all users shows a fatal error message {Fatal error: Call to undefined method MoodleQuickForm_hidden::MoodleQuickForm_hidden() in .. while browsing users in your Moodle installation. The possible reason could be the PHP version issue.

The easiest way to resolve is add in HTML_QuickForm_element (moodle/lib/pear/HTML/QuickForm/element.php)

public function __call($name, $args) {
    $name = str_replace('MoodleQuickForm_', '', $name);

    if ($name == 'passwordunmask') {
        $name = 'password';

    return call_user_func_array(array($this, 'HTML_QuickForm_'.$name), $args);


PHP Validations

Email Validation:

if(!filter_var($email, FILTER_VALIDATE_EMAIL))
echo “E-mail is not valid”;


Integer Validation:

is_int($var)  or is_integer($var)

Returns true/false

Valid: 2, 4, 10

Invalid: “2”, 2.5


Float Validation:


Returns true/false

Valid: 11.5, 1e4

Invalid: “2.5”, 4, 0


Numeric Validation:


Returns true/false

Valid: 40, 1e4, 1550, 9.5

Invalid: “2.5”


String Validation:


Returns true/false

Valid: ‘abc’, “abc”

Invalid: 11.5, 23, true

Javascript Select All Checkboxes

Ok so last week I was trying to implement Check ALL / Unckeck ALL functionality. The form was having a root checkbox and by selecting this checkbox all the checkboxes on form should also be selected. Same for uncheck all should be unchecked.

There are many code snippets available but the problem was I was submitting this form to a PHP script and to process the checked entires PHP needs an array. So the checkboxes name should be something like chktopic[],

<input type="checkbox" name="chktopic[]” value=”topic_1″ />
<input type="checkbox" name="chktopic[]” value=”topic_2″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_3″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_4″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_5″ />

and then in PHP script you can use it like

$topics = $_POST[“chktopic”];
$totaltopics = count($topics);
for ($i=0; $i<$totaltopics; $i++) {
$status = deleteTopic($topics[$i]);

You can see I am trying to Delete all the selected topics. That was the PHP part but how about JavaScript how we will implement check all / uncheck all. So initially I tried with is function

My root checkbox

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics.chktopic,this)”>

and the JS function was

function checkAll(checkname, root) {
for (i = 0; i < checkname.length; i++)
checkname[i].checked = root.checked? true:false

But this function was not working as you can see the name is having [] (an array), if you use a single name (like name=”chktopic”) for all checkboxes this function will work smoothly but then PHP will refuse, as PHP needs an array.

So to handle this situation we will use the same JavaScript function but on root checkboxes we will do a tweak

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics[‘chktopic[]’],this)”>

Simple right 🙂


moodle – Enroll User in a Course

This time for moodlers, have you ever faced such type of need, that you want to enrol user directly in a course using some predefined moodle functions. I was in need for this just after payment success, so thought I should share with you friends..


$userid = 'jaswanttak'; // this is user's idnumber
$courseid = 'TEST-01'; // this is course's idnumber

// if you want to use only id than in get_records() you will have to write id in second parameter

$user = get_record("user", "idnumber", $userid);
$course = get_record("course", "idnumber", $courseid);

if (!enrol_into_course($course, $user, 'paypal')) { // paypal is enrollment method for my system you will use yours
echo 'error';
} else {
echo 'success';


Activate Oracle on XAMPP for Windows : OCI8

If you want to connect with Oracle database using PHP script you will have to do some effort. Because with the default installation of XAMPP for Windows, we don’t get PHP Oracle connectivity enabled. This can be enabled easily when you need to connect to a Oracle Database from your PHP application/script. PHP has got the OCI8 extension, which provides Oracle connectivity to PHP application, and OCI8 uses Oracle Instant Client Package to get Oracle specific functions.

I had the need to connect to a Oracle Database from a PHP script in one of my recent projects, the following is what I did to enable Oracle connectivity in XAMPP for Windows.

1. In your XAMPP Start Page, go to phpinfo, look for string oci8. If string found it indicate that connection to oracle is available, otherwise to activate connection do the following steps:
2. Open the currently used php.ini file by looking at the phpinfo, from the XAMPP folder.
3. Find string ;extension=php_oci8.dll. Remove the semicolon (;) ahead of the string to activate the oracle extension.
4. Save the php.ini file.
5. Download the “Instant Client Package – Basic” for Windows from the OTN Instant Client page. Unzip it to c:\instantclient_11_1
6. Edit the PATH environment setting and add c:\instantclient_11_1 before any other Oracle directories. For example, on Windows XP, follow Start -> Control Panel -> System -> Advanced -> Environment Variables and edit PATH in the System variables list.
7. Set desired Oracle globalization language environment variables such as NLS_LANG. If nothing is set, a default local environment will be assumed. See An Overview on Globalizing Oracle PHP Applications for more details.
8. Unset Oracle variables such as ORACLE_HOME and ORACLE_SID, which are unnecessary with Instant Client (if they are set previously).
9. Restart XAMPP (or Start if its not already started).
10. To make sure that connection to oracle database has successfully activated, go to phpinfo. Find string: oci8. If found, then XAMPP can now communicate with Oracle Database.

The steps to do the same on Linux are almost similar, except there you will use the Linux versions of the packages and setting PATH variables would be different.

To test the connection you can use this script

$conn = oci_connect('username', 'password', 'host:port/servicename');
$query = 'select table_name from user_tables';
$stid = oci_parse($conn, $query);
oci_execute($stid, OCI_DEFAULT);
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
foreach ($row as $item) {
echo $item." | ";
echo "