Medoo查询操作
数据库查询
select($table, $columns, $where)
- table [string]表名.
- columns [string/array]要查询的字段名.
- where (optional) [array]查询的条件.
创建一个公共文件 connect.php
<?php
// 如果你使用php的依赖安装。可以使用以下方法自动载入
require 'vendor/autoload.php';
//导入命名空间
use Medoo\Medoo as Db;
// 配置数据库
$config = [
// 必选
'database_type' => 'mysql',
'database_name' => 'php_edu',
'server' => 'localhost',
'username' => 'wjh',
'password' => '1010',
// [可选]
'charset' => 'utf8',
'port' => 3306,
];
//实例化Medoo类,创建db对象
$db = new Db($config);
查询实例
<?php
/**
* Medoo 查询操作
*/
//1. 实例化Medoo数据库
require __DIR__ . '/connect.php';
//2. 执行查询
$table = 'user';
$fields = ['id', 'name', 'age'];
//查询状态为1的用户
$where = ['status'=>1];
//查询年龄大于50的用户
$where = ['age[>]'=>50];
//查询年龄大于50且性别为男的用户
$where = ['AND'=>['age[>]'=>50, 'sex'=>0]];
$rows = $db->select($table, $fields, $where);
foreach ($rows as $row){
echo print_r($row, true) . '<hr>';
}
Medoo插入操作
插入数据到表中
insert($table, $data)
- table[string] 表名
- data[array] 插入到表中的数据
插入实例
<?php
require __DIR__ . '/connect.php';
$data = [
'name' => '杨过',
'sex' => 1,
'age' => 26,
'email'=> 'yg@php.cn',
'password' => sha1('123456'),
'status' => 1,
'create_time'=> time()
];
//返回PDO预处理对象
$stmt = $db->insert('user', $data);
echo print_r($stmt, true);
//输出错误信息
echo print_r($stmt->errorInfo(), true);
Medoo更新操作
修改表数据
update ($table, $data, $where)
- table[string] 表名
- data[array] 修改的数据
- where(optional)[array] WHERE条件. [可选]
更新实例
<?php
//1. 实例化Medoo数据库
require __DIR__ . '/connect.php';
//数据表
$table = 'user';
//更新数据
$data = [
'name'=>'欧阳克',
'sex' =>1,
];
$data = [
'name'=>'洪七公',
//年龄 +=1
'age[+]' =>1,
];
//更新条件
$where = [
'name'=>'hongqigong'
];
//返回预处理对象
$stmt = $db->update($table, $data, $where);
//输出错误信息
echo print_r($stmt->errorInfo(), true);
Medoo删除操作
删除表中的数据
delete ($table, $where)
- table[string] 表名
- where[array] WHERE 删除条件.
删除实例
<?php
//1. 实例化Medoo数据库
require __DIR__ . '/connect.php';
//数据表
$table = 'user';
//删除条件
$where = [
'name'=>'yangkang'
];
//返回预处理对象
$stmt = $db->delete($table, $where);
//输出错误信息
echo print_r($stmt->errorInfo(), true);
参考资料:
[1] Medoo框架手册