博客列表 >thinkphp数据库操作——2018年5月24日

thinkphp数据库操作——2018年5月24日

沈斌的博客
沈斌的博客原创
2018年05月24日 07:47:491208浏览

thinkphp的数据库操作,使用链式写法。

文件路径:tp/application/index/controller/Test.php

访问其中的方法时,使用 tp.top/index.php/index/test/update,查看执行的结果

实例

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

class Test
{
    public function find(){
        $res = Db::table('staf')
            ->field('name,sex,salary')
            ->where('staff_id',2)
            ->find();
        dump($res);
    }

    public function select()
    {
        $res=Db::table('staf')
            ->field('name,sex,salary')
            ->where('salary','>',3000)
            ->order('salary','DESC')
            ->limit(5)
            ->select();
        dump($res);
    }

    public function insert()
    {
        $data=[
            'name'=>'halc',
            'sex'=>1,
            'age'=>45,
            'salary'=>6800
        ];

        $num=Db::table('staf')->data($data)->insert();
        $id=Db::getLastInsId();
        return $num ? '添加,id='.$id : '没有被添加';

    }

    public function insertMulti()
    {
        $data=[
            ['name'=>'jla','sex'=>0,'age'=>35,'salary'=>7800],
            ['name'=>'alice','sex'=>0,'age'=>45,'salary'=>8800],
            ['name'=>'beal','sex'=>1,'age'=>50,'salary'=>9800],
        ];

        $num = DB::table('staf')->data($data)->insertAll();
        return $num ? '添加成功'.$num.'条记录':'没有记录添加';
    }

    public function update()
    {
        $num = Db::table('staf')
            ->where('salary','<',3600)
            ->data(['salary'=>Db::raw('salary+1000')])
            ->update();

        $num1=Db::table('staf')
            ->update(['sex'=>1,'staff_id'=>9]);
        return $num ? '更新成功'.$num.'条记录' :'没有记录更新';
    }

    public function delete()
    {
        $num=Db::table('staf')->delete(12);
        return $num ? '删除了'.$num.'条记录' :'没有删除';

    }
}
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议