moodle笔记之-数据库操作

引入

<?php

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();

参数详解

define('IGNORE_MISSING', 0);//兼容模式如果没有找到记录返回false,显示调试警告如果多个记录发现


define('IGNORE_MULTIPLE', 1);//与 IGNORE_MISSING相似但如果多个记录发现不显示调试警告,不建议使用

define('MUST_EXIST', 2);//显示一个记录必须存!在如果发现没有记录或者多个记录会抛出异常

$conditions:可选的数组默认为null

$sort:可选排序默认为空

$fields:要查询的字段(可以是*或者X和字段名;多个用,隔开)。默认为*

$limitfrom=0:返回记录的子集,开始在这一点上(可选)默认为0

$limitnum:返回一个许多记录组成的子集总共(可选,如果$ limitfrom设置那么它也是必需的)默认为0

$table:要查询的表名

$select:要查询的sql片段

$params:一个sql字段值的参数组
View Code

1.统计函数

//看到有多少匹配给定标准的记录
//①count_records:$DB->count_records($table, array $conditions=null)

//统计函数相当于:select count(*) from mdl_user;
echo $DB->count_records('user').'<br><br>'; // 查询有多少用户

// ②$DB->count_records_select($table, $select, array $params=null, $countitem="COUNT('x')")

// 注意:COUNT('x')等同于COUNT(*)
echo $DB->count_records_select('user', 'firstname=?', array('同学'),"COUNT('x')").'<br><br>';

//③$DB->count_records_sql($sql, array $params=null)

$sql_1="select count(id)from {user} where firstname = ? ";
echo '<pre>';
echo $DB->count_records_sql($sql_1, array('同学')) .'<br />';

//
2、获取单个记录 只能显示一个记录相当于加了个limit 1
//
// ①get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING)

//所有在函数中的条件参数都用array(字段名=>字段值)
$person = $DB->get_record('user', array('firstname'=>'li'));//如果数据库中与两条相同的数据只显示一条
//get_record :相当于select * from 表名 where firstname='li' limit 1;
$aaa=$DB->get_record('user', array('id' =>2), 'lastname,firstname', MUST_EXIST);
//相当于select lastname,firstname from mdl_user where id =2 limit 1;
//var_dump($aaa);

//② $DB->get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING)

$record = $DB->get_record_select('user', "id = ?", array(2),'lastname,firstname',IGNORE_MISSING);
//var_dump($record);
//相当于select lastname,firstname from mdl_user where id =2 limit 2;

//③ 当使用xxx_sql()函数,表名之间必须附上花括号

$user = $DB->get_record_sql('select * from {user} where id = ?', array(2));
//var_dump($user);
//select * from {user} where id = 2 limit 1;

// $DB->get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING);

//所有在函数$ params参数是用于在SQL语句中填充占位符的值的数组。两个问号和命名占位符可以使用。需要注意的是名为PARAMS 必须是唯一的,即使传递的值是相同的。
//问号占位符
$DB->get_record_sql('SELECT * FROM {user} WHERE firstname = ? AND lastname = ?',array('Martin', 'Dougiamas'));
//问号占位符
$DB->get_record_sql('SELECT * FROM {user} WHERE firstname = :firstname AND lastname = :lastname',array('firstname'=>'Martin', 'lastname'=>'Dougiamas'));

//
3、得到一个散列数组记录 可以显示多个记录
//
//①$DB->get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)

$params_a = array('lastname' => '高永红', 'firstname' =>'同学');
$instances = $DB->get_records('user', $params_a, 'lastname, id desc','id,lastname,firstname');//desc倒序 asc正序
echo '<pre>';
var_dump($instances);

//②$DB->get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)

$ccc=$DB->get_records_select('user', 'lastname=?and firstname=?', array('高永红','同学'), 'id desc', 'id,lastname,firstname', 0, 0);
var_dump($ccc);

//③ $DB->get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);

他的语法如下
*/ 
$bbb=$DB->get_records_sql('select * from {user} where firstname=?', array('同学'),0,0);

出来的结果是数组里面套对象并且每个对象还对应其id值,有段哦少记录显示多少出来如:

/*array(52) {
[7]=>
object(stdClass)#179 (53) {
["id"]=>
string(1) "7"
.....
注意get_record_sql不管查到几条数据只显示一条数据

//④ $DB->get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom='', $limitnum='')

$re = $DB->get_records_list('user', 'id', array(2, 5));
//var_dump($re);
//相当于SELECT * FROM {} WHERE course IN (?,?)

//
4、获取数据一个关联数组的键/值对
//

// ① $DB->get_records_menu($table,array$conditions=null,$sort='',$fields='*',$limitfrom=0,$limitnum=0)

//    如果满足所有给定的条件,那么会把前两列的记录作为一个关联数组,。
$ddd=$DB->get_records_menu('user',array('lastname' => '高永红', 'firstname' =>'同学'),'id desc','id,lastname,firstname',0,0);
/*
结果如下:
array(2) {
[59]=>
string(9) "高永红"
[58]=>
string(9) "高永红"
}

*/
$ddd=$DB->get_records_menu('user',array('lastname' => '高永红', 'firstname' =>'同学'),'id desc','username,email,lastname,firstname',0,0);
/*
array(2) {
[11111111]=>
string(15) "aaaaaaaa@qq.com"
[29481804]=>
string(15) "29481804@qq.com"
}

*/

//可以看出不管查询出多少列(字段)只取前两列并且将第一列的作为键第二列作为值组成一个新数组

//②get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)

$eee=$DB->get_records_select_menu('user','lastname=? and firstname=?',array('高永红', '同学'),'id desc','username,email,lastname,firstname',0,0);
/*

array(2) {
[11111111]=>
string(15) "aaaaaaaa@qq.com"
[29481804]=>
string(15) "29481804@qq.com"
}

*/

//③$DB->get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0)

$sql_f='select username,email,lastname,firstname from {user} where lastname=? and firstname = ?';
$fff=$DB->get_records_sql_menu($sql_f, array('高永红', '同学'),0,0);
/*

array(2) {
[11111111]=>
string(15) "aaaaaaaa@qq.com"
[29481804]=>
string(15) "29481804@qq.com"
}

*/


//
//如果存在一条记录返回true不存在则返回false
//

// ①$DB->record_exists($table, array $conditions=null)

$ggg=$DB->record_exists('user', array('id'=>2));
var_dump($ggg);

//② $DB->record_exists_select($table, $select, array $params=null)

$hhh=$DB->record_exists_select('user', 'id=?', array(2));
var_dump($hhh);

//③   $DB->record_exists_sql($sql, array $params=null) (下面这句的sql语句可能不太正确);

$sql_15="select id,lastname,country from {user} where firstname = ? group by country having count(id)>1";
echo '<pre>';
$result15=$DB->record_exists_sql($sql_15, array('同学')) ;
var_dump($result15);

//
//得到一个记录的某个特定字段值
//

//16 $DB->get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING)
// 注意; $conditions查询出来的值必须是单条记录多条记录会报错(可以这样认为他们两个都是独一无二的)
// 下面这个例子就是从一个叫张丽的字段中查出对应的id

$iii=$DB->get_field('user', 'id', array('lastname'=>'张丽'),IGNORE_MISSING);
var_dump($iii);

//17 $DB->get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING)

$jjj=$DB->get_field_select('user', 'id', 'lastname=?', array('张丽'), IGNORE_MISSING);
var_dump($jjj);

//18 $DB->get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING)

echo $DB->get_field_sql("select id from {user} where lastname=?", array('张丽'), IGNORE_MISSING).'<br>';

//
//从各个记录中得到一个特定的字段值
//
//19 $DB->get_fieldset_select($table, $return, $select, array $params=null)

$kkk=$DB->get_fieldset_select('user', 'id','firstname=?', array('同学'));
//var_dump($kkk);

//20 $DB->get_fieldset_sql($sql, array $params=null)

$lll=$DB->get_fieldset_sql('select id from {user} where firstname=?', array('同学'));
//var_dump($lll);

//
//达到条件时在数据库中为某个设置特定字段设置新值(修改字段值)修改成功返回true
//

//21 $DB->set_field($table, $newfield, $newvalue, array $conditions=null)

$mmm=$DB->set_field('user', 'username', 'myusername', array('username'=>'11111111'));
var_dump($mmm);

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ 删除数据 +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//删除单条数据
//22 $DB->delete_records($table, array $conditions=null)
$DB->delete_records('user', array('id'=>60));

//23 $DB->delete_records_select($table, $select, array $params=null)
$DB->delete_records_select('user', 'id=?', array(61));

//删除多条数据
//24 delete_records_list($table, $field, array $values)
//删除一个记录从表中(哪个表)一个字段匹配的值列表
//$field:搜索要删除的的字段名
//array $values 要删除的该字段的值的数组
$DB->delete_records_list('user', 'id', array(65,67,68));


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +
// +
// 插入数据 +
// +
// +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//$DB->insert_record($table, $dataobject, $returnid=true, $bulk=false)
//$dataobject:一个或多个字段的值记录的数据对象
//$returnid:新创建的记录条目的id应该返回?如果这个选项不是请求然后返回true / false
// $bulk 是否重复插入
// 返回true或者新的id
//
/*
$person = new StdClass();
$person->auth = 'manual';
$person->confirmed = 1;
$person->mnethostid = 1;
$person->lastlogin = time();
$person->currentlogin = time();

$person->username = "lichihua1";
$person->password = hash_internal_user_password('a173512');
//$person->idnumber = $person->username;
$person->firstname = "李四";
$person->lastname = "老师";
$person->email = "firstname@gmail.com";
$person->city = "蓬溪";
$person->country = "CN";
$person->lang = "zh_cn";

echo $person->id = $DB->insert_record('user', $person);
//插入前insert_record会将上面的数据对象转化成数组$dataobject = (array)$person;
get_columns($table)方法会将表的字段信息展示出来然后用foreach循环和上面对象转换的进行比较筛选然过滤后在返回来
然后normalise_value()方法会将返回回来的数组的字段对应的键和值进行转换后再次返回回来
最后再将上面处理的放入insert_record_raw()方法中 进行插入操作
*/
echo '1111111111111111111111111111111111111111<br>';
$record = new stdClass();
$record->auth = 'manual';
$record->confirmed = 1;
$record->mnethostid = 1;
$record->lastlogin = time();
$record->currentlogin = time();
$record->username = "lichihua4";
$record->firstname = "李四4";
$record->lastname = "老师";
$record->password = hash_internal_user_password('123');
//$lastinsertid = $DB->insert_record('user', $record, false);//成功不返回id返回true的操作默认是返回id的
//$lastinsertid = $DB->insert_record('user', $record);//成功返回id的操作默认是返回id的
//var_dump($lastinsertid);
/*
$record1 = new stdClass();
$record1->name = 'overview';
$record1->displayorder = '10000';
$record2 = new stdClass();
$record2->name = 'overview';
$record2->displayorder = '10000';
$records = array($record1, $record2);
$lastinsertid = $DB->insert_records('quiz_report', $records);
*/


/*
//insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false)
//这个是插入的过程函数不会用到它
//插入新记录到数据库,尽可能快,没有安全检查,lob不支持
//$params:数据记录的对象或数组
//$returnid:返回它的插入记录(return it of inserted record)
// $bulk:重复插入的预期
//$customsequence:如果“id”被包括在$params参数里,那么禁用$returnid
//返回值true或者插入时获取的id即$customsequence为true是返回id值false是返回true
//
//工作流程:1如果参数不是数组那么经他转化成数组
//2如果$customsequence为真判断$params中是否有id如果若果没有抛出错误提示并且将$customsequence的值改为false。如果$customsequence为假按么销毁$params中的id(unset($params['id'])
//3、判断参数是否为空为空的话抛出错误提示
//4、//取得数组的键名并用,将其拼接成字符串
// $qms = array_fill(0, count($params), '?');//用问号填充数组填充次数为参数的个数
// $qms = implode(',', $qms);//将?填充好的数组之后,在用,链接成一个字符串
//这时的sql语句为INSERT INTO 表名 (字段名-参数1,参数2,参数3) VALUES(?,?,?...)
//5 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);将处理好的sql语句参数等依次分别付给左边变量。。。执行插入操作
*/

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ 修改(数据)记录 +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


//$DB->update_record($table, $dataobject, $bulk=false)
$dataobject = new stdClass();
$dataobject->id = 73;
$dataobject->username = "lichihua004";
$dataobject->firstname = "李四004";
$dataobject->password = hash_internal_user_password('00123');
//$DB->update_record('user', $dataobject, false);

//如果要使用任意的sql执行更复杂的更新
//$DB->execute($sql, array $parms=null)
//不要使用这个使数据库结构变化,用database_manager方法代替!
//database_manager

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ 使用记录集 +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
其中从DB中检索的记录的数量高,get_records_xxx()函数上述远非最佳的,因为它们加载在存储器中的所有记录在同一时间。在这种情况下,强烈建议使用这些get_recordset_xxx()函数来代替,其中用一个很好的机制来遍历所有的目标记录,并节省了大量的内存。只有一件事是绝对重要的:不要忘记使用后关闭该记录集! (这将释放在RDBMS大量的资源)。下面是遍历使用get_recordset_xxx()函数记录的一般方式:
这是一般方法遍历记录使用get_recordset_xxx()函数:
$rs=$DB->get_recordset(....){
foreach($rsas$record){
// Do whatever you want with this record
}
$rs->close();// Don't forget to close the recordset!
这是可用功能列表(100%搭配get_records_xxx()以上):
o $DB->get_recordset($table,array$conditions=null,$sort='',$fields='*',$limitfrom=0,$limitnum=0)
/// Get a number of records as a moodle_recordset where all the given conditions met.
o $DB->get_recordset_select($table,$select,array$params=null,$sort='',$fields='*',$limitfrom=0,$limitnum=0)
/// Get a number of records as a moodle_recordset which match a particular WHERE clause.
o $DB->get_recordset_sql($sql,array$params=null,$limitfrom=0,$limitnum=0);
/// Get a number of records as a moodle_recordset using a SQL statement.

o $DB->get_recordset_list($table,$field='',$values='',$sort='',$fields='*',$limitfrom='',$limitnum='')
/// Get a number of records as a moodle_recordset where one field matches one list of values.
与get_record功能,您不能使用rs = = true或$!空(rs)来确定任何记录被发现。记录集这样的实现标准的PHP迭代器接口(http://uk.php.net/manual/en/class.iterator.php)
所以,
不像get_record功能,你不能使用$rs == true 或者 !empty($rs),以确定是否发现任何记录。记录集实现标准的PHP Iterator接口(http://uk.php.net/manual/en/class.iterator.php) 所以
if($rs->valid()){
// The recordset contains records.
}

*/


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ 委托交易(事务处理) +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

/*
//启动事物
$transaction=$DB->start_delegated_transaction();
//提交?
$transaction->allow_commit();
//回滚
$transaction->rollback($e);
*/
//例子
/*
global $DB;
try {
$transaction = $DB->start_delegated_transaction();
// Insert a record
$DB->insert_record('foo', $object);
$DB->insert_record('bar', $otherobject);

// Assuming the both inserts work, we get to the following line.
$transaction->allow_commit();
} catch(Exception $e) {
$transaction->rollback($e);
}
*/

//$DB->set_debug(true) 调试功能

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ SQL兼容性函数 +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//看不懂省略


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ +
//+ +
//+ 特殊情况 :课程获取 +
//+ +
//+ +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//注意:在2.51版本以上生效
//get_course($fields)比如你想要根据课程id查这门课程的记录那么用get_course($courseid)替换:$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);

//get_courses(此括号里无参数):这个函数是获取当前所有的课程
$courses = get_courses();
var_dump($courses);


echo'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br />';
$capabilityname='plugintype/pluginname:capabilityname';
$pattern='|[/:]|';
$arr=preg_split($pattern,$capabilityname);//这里是用/或者:分割字符串
var_dump($arr);
list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
var_dump($type);
echo '';
//list()把数组中的值付给一些变量
//preg_split(正则模式,要处理的字符串) — 通过一个正则表达式分隔字符串
echo'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br />';

原文地址:https://www.cnblogs.com/lichihua/p/5706285.html