美文网首页ThinkPhp5入门
TP5数据库原生查询

TP5数据库原生查询

作者: 傲娇的泰迪 | 来源:发表于2018-01-12 09:07 被阅读0次
原生查询

在\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);
  }
}
?>

相关文章

网友评论

    本文标题:TP5数据库原生查询

    本文链接:https://www.haomeiwen.com/subject/dbzznxtx.html