在\think\Db中有query和execute方法,用来读和写数据库。
打开index.php文件:
<?php
namespace app\index\controller;
use think\Db;
class Index
{
public function demo()
{
//1.查询操作:工资大于4000元的员工信息
$sql = "select name,salary,dept from staff where salary > 4000";
$result = Db::query($sql);
dump($result);
}
}
?>
接下来用另外一种形式:
<?php
namespace app\index\controller;
use think\Db;
class Index
{
public function demo()
{
//1.查询操作:工资大于4000元的员工信息,用命名占位符进行参数绑定
$sql = "select name,salary,dept from staff where salary > :salary"; //:salary就是命名占位符
$result = Db::query($sql,['salary'=>4000]);
dump($result);
//2.更新操作,将id=1004的记录,salary增加1000
$sql = "update staff set salary = salary+1000 where id=:id";
$result = Db::execute($sql,['id'=>1004]);
dump($result);
//3.插入操作:默认添加到表的尾部
$sql = "insert into staff (name,sex,age) values(:name,:sex,:age)";
$result - Db::execute($sql,['name'=>'朱老师','sex'=>1,'age'=>30]);
dump($result);
//删除操作:id=1010的记录删除
$sql = "delete from staff where id=:id";
$result = Db::execute($sql,['id'=>1010]);
dump($result);
}
}
?>