Blogger Information
Blog 5
fans 0
comment 0
visits 2218
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库操作—2018年5月23日12时28分
候磊的博客
Original
403 people have browsed it
<?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.'条记录' : '没有记录被删除';	
	}
}		
Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post