thinkPHP中对数据库操作的几种简单方法

访问方式http://localhost/tp5/public/index.php/index/index/db

注:find()和select()的区别就是,find()只会显示出第一条数据的值

原生查询

<?php
namespace app\index\controller;
use think\Request;
use think\Db;

class Index
{
    public function index()
    {
        //return '';
    }
    public function db() {
      //插入数据,返回的是影响的行数
      //$result = Db::execute('insert into think_data (name, status) values ("周杰伦", 1)');
      //查询数据,返回的是查询出的数组
      $result = Db::query('select * from think_data');
      dump($result);
    }
}

构造器查询

public function db() {
      //插入记录
      //$result = Db::table('think_data')->insert(['name' => '张天爱', 'status' => 1]);

      //更新数据
      //$result = Db::table('think_data')->where('id', 1)->update(['name' => '刘德华', 'status' => 0]);

      //查询所有、部分
      //$result = Db::table('think_data')->select();
      $result = Db::table('think_data')->where('id', 2)->select();
      dump($result);
    }

还可以使用name方法,此时不需要使用前缀码,即Db::name('data'),其他不需要改动,效果是一样的。
使用助手函数,创建一个$db对象,可以进一步简化构造器查询的代码,但是使用助手函数,会大幅度增加内存的占用(每次使用,都会新生成一个$db对象),所以,我们应该尽量少使用助手函数。

//使用助手函数调用
      $db = db('data');
      $result = $db->insert(['name' => '黄渤', 'status' => 1]);
      dump($result);

使用链式操作来实现对数据库的复杂操作

public function db() {
      //一个有限制的查询
      $list = Db::name('data')->where('status', 1)->field('id, ', 'name')->order('id', 'desc')->limit(2)->select();
      dump($list);
    }

通过定义模型来操作数据库

通过定义一个新的模型,在controller(控制器目录)的同级目录下定义一个Model文件夹,定义一个User.php文件。
然后就可以在控制器目录下新建相关的触发器了。

<?php
  namespace app\index\controller;
  use app\index\model\User as UserModel; //当模型名称与触发器名称相同时,需要改名称

  /**
   *定义触发器来使用模型
   */
  class User
  {
    public function add() {
      $user['name'] = '雾里看花';
      $user['email'] = 'kanhua@qq.com';
      $user['birthday'] = strtotime('1991-6-12');
      if($result = UserModel::create($user)) {
        return '用户新增成功';
      } else {
        return '用户新增失败';
      }
    }
  }

使用模型实现批量操作

public function addList() {
      $user = new UserModel();
      $list = [
        ['name' => '镜花水月', 'email' => 'jinghua@qq.com', 'birthday' => strtotime('1972-12-11')],
        ['name' => '水月洞天', 'email' => 'shuiyue@qq.com', 'birthday' => strtotime('1972-1-23')]
      ];

      if($user->saveAll($list)) {
        return '批量插入成功';
      } else {
        return '批量插入失败';
      }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容