博客列表 >数据库操作—2018年5月23日12时28分

数据库操作—2018年5月23日12时28分

候磊的博客
候磊的博客原创
2018年05月24日 13:03:19391浏览
<?php 
namespace app\index\controller;
use think\Db;

class Query
{
	public function find()
	{
	        //find方法参数主键查询,取出一条数据
		$res = Db::table('staff')
			->find(10);

		$res = Db::table('staff')
			->where('staff_id',1)
			->find();
			
               //field选择查询的数据库字段
		$res = Db::table('staff')
			->field(['name'=>'姓名','sex'=>'性别','age'=>'年龄'])
			->where('staff_id',1)
			->find();
			dump($res);
	}


	public function select()
	{
		//select查询多条记录
		//order按条件排序
		//limit取出数据数量
		$res = Db::table('staff')
			->field(['name'=>'姓名','salary'=>'工资'])
			->where('salary','>',3000)
			->order('salary','DESC')
			->limit(5)
			->select();
                dump($res);
	}

	public function insert()
	{
		//insert新增一条数据 
		$data = [
			'name' => '张三',
			'sex' => 0,
			'age' => 16,
			'salary' => 5100
		];
		$num = Db::table('staff')->insert($data);
		$id = Db::getLastInsID();
		
		return $id ? '添加成功,id='.$id : '没有记录被添加';

		$num = Db::table('staff')->data($data)->insert();
		$id = Db::getLastInsID();
		return $num ? '添加成功,id='.$id : '没有记录被添加';
		

		// insertAll新增多条记录
		$data = [
			['name' => '张飞','sex' => 0,'age' => 48,'salary' => 6900],
			['name' => '刘备','sex' => 0,'age' => 58,'salary' => 4500],
			['name' => '关羽','sex' => 0,'age' => 53,'salary' => 4700],
		];
		$num = Db::table('staff')->data($data)->insertAll();
		return $num ? '添加'.$num.'条记录' : '没有记录被添加';		

	}


	public function update()
	{
		//update更新
		$num = Db::table('staff')
			->where('salary','<=',4000)
			//Db::raw()引用原salary字段的值
			->data(['salary'=> Db::raw('salary+1000')])
			->update();
			
		$num = Db::table('staff')
			->update(['sex'=>1,'staff_id'=>19]);
		return $num ? '更新'.$num.'条记录' : '没有记录被更新';	
	}

	public function delete()
	{
		//delete删除
		$num = Db::table('staff')->where('salary','>',10000)->delete();

		$num = Db::table('staff')->delete(true);  //数据表后面还要用,此功能课后练习

		return $num ? '删除'.$num.'条记录' : '没有记录被删除';	
	}
}		
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议