tp6 CURD示例
1、数据表结构:
CREATE TABLE `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(10) DEFAULT NULL,
`create_time` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2、新建一个Tp6项目,并配置数据库;

3、添加数据示例:
public function create(){
$data = array(
'name' => 'tom',
'age'=> 14,
'create_time'=> time()
);
$int = \think\facade\Db::name('users')->insert($data);
if($int){
echo "插入成功!";
}else{
echo "插入失败!";
}
}



4、更新数据示例:
将id=1的name改为thinkphp;
将id=4的name改为php;
public function update(){
//第一种修改
$int = \think\facade\Db::name('users')
->save(['id' => 1, 'name' => 'thinkphp']);
echo "\$int:".$int;
echo "<br/>";
//第二种修改
$ret = \think\facade\Db::name('users')
->where('id', 4)
->update(['name' => 'php']);
echo "\$ret:".$ret;
}




5、查询数据示例:
public function select()
{
//单条记录
$row = \think\facade\Db::name('users')->where('id', 1)->find();
print_r($row);
//多条结果集(更多链式用法,where,limit,order等等)
$result = \think\facade\Db::name('users')->select();
print_r($result);
}


6、删除数据示例:
/**
*
* 删除
*
*/
public function delete(){
/**根据主键删除**/
//删除主键为1的记录(users表的主键为id,可以理解为where id=1)
//$int1 = \think\facade\Db::name('users')->delete(1);
//删除多条记录,删除主键为1,2,3的记录(users表的主键为id)
//$int2 = \think\facade\Db::name('users')->delete([1,2,3]);
/**根据条件删除**/
$int3 = \think\facade\Db::name('users')->where('id',1)->delete();
//$int4 = \think\facade\Db::name('users')->where('age','<',16)->delete();
if($int3){
echo "删除成功!";
}else{
echo "删除失败!";
}
}

