Query resulting in a simple list

Query resulting in a simple list

by Andrew P -
Number of replies: 3
Hello! 


I have been searching wildly but can't find a solution simple enough for my needs. Hopefully this question is OK here.

I wish to have a page eg. /local/test.php that queries the database and provides a simple list. I have done this successfully to echo the current userid, so I know it works using require('../config.php');

I am struggling to get a list of all user names. Sounds so easy! What is the correct way to query the database then cycle through the results to print these as rows in a table? 

I know there is lots of info out there about queries, and also about how to print mysql queries as rows but there is much less about how to construct a single php page that has the query and prints the results.

Can anyone please provide a sample php page that simply does this?


Thanks so much!



Average of ratings: -
In reply to Andrew P

Re: Query resulting in a simple list

by Chris Fryer -

Tim's example is probably a bit overkill for your requirement.  As I read it you just want a list of usernames, so this would probably do:

<?php
require_once('../config.php');
$results = $DB->get_records_menu('user', null, 'username asc', 'id, username');
echo '<pre>';
foreach ($results as $id => $username) {
  echo "$username\n";
}
echo '</pre>';

Moodle's Data Manipulation API has done most of the heavy lifting for you.

https://docs.moodle.org/dev/Data_manipulation_API

The arguments passed to moodle_database::get_records_menu are: 

  • the table you want to query ('user');
  • any predicates for your query (null, because you want them all);
  • the column by, and order in which, you want the results sorted; and
  • the columns you want from the database

The rest is ordinary PHP for looping through an associative array

Hope this helps,

Chris

In reply to Chris Fryer

Re: Query resulting in a simple list

by Andrew P -

Thanks so much, Tim and Chris. Although Tim's link will come in handy, Chris' snippet really got what I needed. I have altered as below to get a list of the current user's grades. This will then be easy for me to format into a more friendly format than the user report.


One question, though, how do I get the finalgrade as a Letter Grade as well??

Thanks again,

Andrew

<?php

require_once('../config.php');

$currentUser = 27; // testing for Sample Student

$assignmentID = $DB->get_records_menu('grade_grades', array('userid'=>$currentUser), 'itemid asc', 'itemid, finalgrade');


echo '<pre>';

foreach ($assignmentID as $itemid => $finalgrade) {

echo $currentUser; echo "($itemid)"; echo (int)$finalgrade."<br>";  

}

echo '</pre>';

?>