correct way to make an sql select in moodle

correct way to make an sql select in moodle

by Vaduvoiu Tiberiu -
Number of replies: 1
Hi,

I'm trying to add some code in my local moodle installation. At this point I need to do a sql select in a table and write the results in a txt/log file.

I'm not a php guru so I usually do it the old fashion way using
$sql="select..."
$rs=mysql_query($sql);
while($row=mysql_fetch_array($rs)){

but I've noticed that moodle has some functions that usually do the sql queries and return some kind of variable.
So is there a function in moodle that does the sql and returns an array with the data or is it ok if I use the old way as well?
Average of ratings: -
In reply to Vaduvoiu Tiberiu

Re: correct way to make an sql select in moodle

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
Well, it will work to do it the manual way, but it would be better to use the Moodle functions. All the relevant functions are in lib/dmllib.php. (One benefit of this is that your code will probably then work on any of the databases supported by Moodle, rather than just MySQL.)

A simple case like

SELECT * FROM mdl_user WHERE id = 123;

becomes

get_record('user', 'id', 123);

(See, it is taking care of the table prefix for you.)

A more complex example, like

SELECT * FROM mdl_user WHERE (some complicated condition) ORDER BY lastname, firstname, LIMIT 100;

becomes something like (I am too lazy to look up the order of the arguments just now)

get_records_select('user', '(some complicated condition)', 'lastname, firstname', '*', 0, 100);

Anyway, have a look at the functions in dmllib.php (they are now all well PHPdoced). It is probably also worth searching the code to find places where they are called, to get lots of examples of how they are used.