Moodle: 查询 / 更新 / 添加 / 删除 / 导出 用户 ($DB用法)

1. 添加用户

require_once('config.php'); // config.php under root folder

require_once($CFG->dirroot .'/course/lib.php');
require_once($CFG->libdir .'/filelib.php');

//redirect_if_major_upgrade_required(); 

$person               = new StdClass();
$person->auth         = 'manual';
$person->confirmed    = 1;
$person->mnethostid   = 1;
$person->lastlogin    = time();
$person->currentlogin = time();

$person->username     = "username";
$person->password     = hash_internal_user_password('password');
//$person->idnumber   = $person->username;
$person->firstname    = "firstname";
$person->lastname     = "lastname";
$person->email        = "firstname@gmail.com";
$person->city         = "sf";
$person->country      = "US";
$person->lang         = "en";
		
echo $person->id = $DB->insert_record('user', $person);

2. 查询用户

require_once('config.php'); // config.php under root folder

require_once($CFG->dirroot .'/course/lib.php');
require_once($CFG->libdir .'/filelib.php');

//redirect_if_major_upgrade_required(); 

echo $DB->count_records('user').'<br><br>'; // how many users do you have

$person = $DB->get_record('user', array('username'=>'my_name'));
echo '<pre>'; print_r($person);

3. 更新用户

require_once('config.php');

require_once($CFG->dirroot .'/course/lib.php');
require_once($CFG->libdir .'/filelib.php');

//redirect_if_major_upgrade_required(); 

$person               = new StdClass();
$person->id           = 10370;
$person->password     = hash_internal_user_password('xinxin123');

$DB->update_record('user', $person);

4. 删除用户

require_once('config.php');

require_once($CFG->dirroot .'/course/lib.php');
require_once($CFG->libdir .'/filelib.php');

//redirect_if_major_upgrade_required(); 

$DB->delete_records('user', array('id'=>10546));

5. 导出用户

require_once('config.php');
require_once('../lib/functions.php');
require_once('../lib/array2xml.php');

$conditions = array();
$sort       = 'id desc';
$fields     = 'id,username,firstname,lastname,email,lastlogin,lastip';
$limitfrom  = 0;
$limitnum   = 30;

$students['students'] = objectToArray($DB->get_records('user', $conditions, $sort, $fields, $limitfrom, $limitnum));
//echo '<pre>'; print_r($students);
//echo JSON($students);

header( 'Content-Type:text/html;charset=utf-8');
header('Content-type: text/xml'); 
exit(array2xml($students));

 

更多语法:Moodle: Data manipulation API 数据库操作

原文:Moodle: 查询 / 更新 / 添加 / 删除 / 导出 用户 ($DB用法)

Leave a Reply