<?php
namespace app\index\controller;
use think\Db;
/**
* 框架核心
* 查询构造器
* 系统学习数据库的增删改查:curd
*/
class Demo5{
/**
* 单条查询
*/
public function find(){
$res= Db::table('cash_channel')
->field('id,title')
//->field(['id'=>'编号','title'=>'标题'])
->where('id',1)
->find();
dump(is_null($res)?'没有数据':$res);
}
/**
* 多条查询
*/
public function select(){
$res=Db::table('cash_channel')
->field('id,title')
->where([['id','>=',2]])
->select();
if(empty($res)){
return '没有数据';
}else{
foreach ($res as $row){
dump($row);
}
}
}
/**
* 单条插入
*/
public function insert(){
$data=[
'title'=>'新数据',
'code'=>'xsj',
'account_fields'=>'代付需要的数据'
];
return Db::table('cash_channel')
//->insert($data,true);//mysql数据库时后面加true sql语句为REPLACE INTO
//->data($data)->insert();//data方法包装增强安全性
->insertGetId($data);//插入返回ID 第一步 插入 第二步 返回主键ID
}
/**
* 多条插入
*/
public function insertAll(){
$data=[
[
'title'=>'新数据2',
'code'=>'xsj2',
'account_fields'=>'代付需要的数据2'
],
[
'title'=>'新数据3',
'code'=>'xsj3',
'account_fields'=>'代付需要的数据3'
]
];
return Db::table('cash_channel')->insertAll($data);
}
/**
* 更新
*/
public function update(){
//更新操作必须有条件,否则拒绝执行
return Db::table('cash_channel')
->where('id',5)
->update(['title'=>'更新的数据title']);
//如果更新条件是主键,那么可直接把主键写到更新的数组中
}
/**
* 删除操作
*/
public function delete(){
return Db::table('cash_channel')
->delete(6);
}
/**
* 原生查询
*/
public function query(){
$sql='select * from cash_channel;';
dump(Db::query($sql));
}
/**
* 原生更新 删除 添加
*/
public function execute(){
// return Db::execute("update `cash_channel` set `title`='武松' where `id`=4");
return Db::execute("insert `cash_channel` set `title`='ss';");
// return Db::execute("delete from `cash_channel` where `name`='ss'");
}
}