一.Medoo的安装与配置
1.Medoo的安装 推荐composer安装
* 在cmd中进入项目目录 输入 $ composer require catfan/Medoo 即可安装
* 导入'vendor/autoload.php'; 即可(composer安装)使用
2.Medoo的配置
*导入文件之后,实例化一个Medoo类,将配置参数传入
// 如果你使用php的依赖安装。可以使用以下方法自动载入 require __DIR__.'/vendor/autoload.php'; use Medoo\Medoo as Db; //数据库的配置参数 $config = [ //必填 'database_type'=>'mysql', //数据库类型 'database_name'=>'php_edu', //默认数据库名称 'server'=>'127.0.0.1', //默认数据库主机名 'username'=>'root', //默认用户名 'password'=>'root', //用户密码 //可选 'charset'=>'utf8', //默认字符编码集 'port'=>3306, //默认端口号 ]; //实例化Medoo类,创建db对象 $db = new Db($config);
二.Medoo的查询操作(读)
+ 基本语法: select(表名,字段列表,查询条件)
+ 字段采用数组格式,单字段可使用字符串;
+ 查询条件必须采用数组格式;
+ 返回为数组格式
*条件为字段=值的情况
//1.实例化Medoo框架类 require __DIR__.'/connect.php'; //2.执行查询 $table = 'user'; $fields = ['id','name','age','email']; $where = ['status'=>1]; //返回结果为数组 $rows = $db->select($table, $fields, $where); //$table 表名 $fields 要查询的字段(数组(多个字段)或者字符串(一个字段)) $where查询条件 //遍历输出 foreach ($rows as $value){ echo print_r($value,true).'<hr>'; }
* 条件为大于或者小于等情况 $where = ['age[>]'=>40] //age>40
$table = 'user'; $fields = ['id','name','age','email']; //查询年龄大于50的用户 $where = ['age[>]'=>50]; $rows = $db->select($table, $fields, $where);
* 条件为AND 或者OR $where = ['AND'=>['age[>]'=>30,'status'=>1]] //$where = age>30 AND status=1
//查询年龄小于40,并且性别等于女(1) $where = ['AND'=>['age[<]'=>40,'sex'=>1]]; $rows = $db->select($table, $fields, $where);
三.Medoo写操作(增,删,改)
* 返回PDOStatment,预处理对象,可以用它执行更多的操作
1.1添加操作 insert(表名,要添加的数据)
require __DIR__.'/connect.php'; //2.新增数据 $table = 'user'; $data['name'] = '美国队长'; $data['sex'] = 0; $data['age'] = 98; $data['email'] = 'meiguoduizhang@163.com'; $data['password'] = sha1('123456'); $data['status'] = 1; $data['create_time'] = time(); //3.执行添加操作 $stmt = $db->insert($table,$data); //返回一个PDO预处理对象
1.2 查看新增主键 $db->id() $db Medoo对象
echo '新增主键id'.$db->id().'<hr>';
1.3 查看一下生成SQL语句 $stmt->queryString (属性)
echo 'SQL语句:' .$stmt->queryString.'<hr>';
--------------------------------------------------------------------------------------------------------------------
2.1更新操作 update(表名,要更新的数据,条件)
//1.实例化Medoo框架类 require __DIR__.'/connect.php'; //2.表名 $table = 'user'; //要更新的数据 //$data['name'] = '猎鹰'; //$data['sex'] = 0; $data['age'] = 99; $data['email'] = 'usacaption@163.com'; //$data['password'] = sha1('123456'); //$data['status'] = 1; $data['create_time'] = time(); //更新条件 $where['id'] = 26; //3.执行更新 $stmt = $db->update($table,$data,$where); //返回预处理对象 //查询更新的记录条数 if($stmt->rowCount() > 0){ echo '更新成功了'.$stmt->rowCount().'条记录'; }
2.2更新数据自增,自减等等... $data['age[+]'] = 1; //age=age+1
$data['age[+]'] = 1; //age =age+1 $where['id'] = 28; $stmt = $db->update($table,$data,$where);
3.1删除操作 delete($table,$where) $stmt->rowCount()返回受影响记录条数
//1.实例化Medoo框架类 require __DIR__.'/connect.php'; //2.执行删除 //表名 $table = 'user'; //删除条件 $where['id'] = 30; $stmt = $db->delete($table,$where); //依旧是预处理对象 if($stmt->rowCount() > 0){ echo "<script> alert('删除成功了".$stmt->rowCount()."条记录')</script>";
Medoo 数据库框架 写操作都是返回预处理对象 读操作返回数组