使用composer安装thinkPHP
- 进入工作目录 输入指令
composer create-project topthink/think tpStudy
数据库操作
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
`password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`sex` int(1) NOT NULL DEFAULT 1 COMMENT '性别:默认1男 0女',
`phone` bigint(11) NOT NULL COMMENT '手机',
`email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '邮箱',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '地址',
`status` int(1) NOT NULL DEFAULT 0 COMMENT '状态:伪删除 默认0未删除 1已删除',
`add_time` int(12) NOT NULL COMMENT '注册时间',
`last_time` int(12) NULL DEFAULT NULL COMMENT '最后登录时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
1.添加数据
// 1.添加数据
// 1.1 添加一条数据 insert()
$data = [
'name' => '米粒',
'password' => md5(123456),
'sex' => 0, 'phone' => 18822229999,
'email' => 'mili@php.cn',
'address' => '贵州省贵阳市乌当区',
'add_time' => time()
];
$res = Db::table('user')->insert($data);
print_r($res);
// 1.2 添加多条数据 insertAll()
$data = [
[
'name' => '暖树',
'password' => md5(123456),
'sex' => 0, 'phone' => 18833339999,
'email' => 'nuanshu@php.cn',
'address' => '贵州省贵阳市花溪区',
'add_time' => time()
],
[
'name' => '景清',
'password' => md5(123456),
'sex' => 1, 'phone' => 18833339999,
'email' => 'jingqing@php.cn',
'address' => '贵州省贵阳市乌当区',
'add_time' => time()
],
[
'name' => '左右',
'password' => md5(123456),
'sex' => 1, 'phone' => 18844449999,
'email' => 'zuoyou@php.cn',
'address' => '贵州省贵阳市南明区',
'add_time' => time()
],
[
'name' => '于心',
'password' => md5(123456),
'sex' => 0, 'phone' => 18855559999,
'email' => 'yuxin@php.cn',
'address' => '贵州省贵阳市南明区',
'add_time' => time()
],
];
$res = Db::table('user')->insertAll($data);
print_r($res);
2.更新数据
// 2.更新数据
$data = ['name' => '于心不忍', 'password' => md5(654321)];
$res = Db::table('user')->where('id', 3)->update($data);
print_r($res);
3.删除数据
// 3.删除数据
// 3.1 根据主键删除一条数据
Db::table('user')->delete(1);
// 3.2 根据主键删除多条数据
Db::table('user')->delete([1, 2, 3]);
// 3.3 条件删除
Db::table('user')->where('id', 1)->delete();
// 3.4 删除id>2的所有数据
Db::table('user')->where('id', '>', 2)->delete();
4.查询数据
// 4.查询数据
// 4.1 查询单条数据 >find()
$res = Db::table('user')->where('id', 1)->find();
print_r($res);
// 4.2 查询多条数据 select 查询的结果集是一个对象 根据使用情况可以使用toArray()转为数组对其操作
$res = Db::table('user')->where('status', 0)->select()->toArray();
print_r($res);
// 4.3 查询某个字段的值 value()
$res = Db::table('user')->where('id', 2)->value('name');
print_r($res);
// 4.4 查询某一列的值 column():第一个参数作为关联数组的值 第二个参数作为关联数组的键
$res = Db::table('user')->column('name', 'id');
print_r($res);
5.原生sql
// 5.支持原生sql语句
$res = Db::query("select * from user LIMIT 2");
print_r($res);