サマリー:<?php namespace app\index\controller; use think\Db; class Query { public function find() { &n
<?php namespace app\index\controller; use think\Db; class Query { public function find() { //查詢單條記錄 $res = Db::table('user') ->find(5);//find里面的參數(shù)為ID號(hào) //通常我們?cè)谑褂胒ind方法時(shí)不在括號(hào)內(nèi)使用參數(shù),而是用where條件來(lái)設(shè)置條件‘ $res = Db::table('user') -> where('id','=',2) -> find(); //指定字段輸出結(jié)果 等于號(hào)可以省略 $res = Db::table('user') //-> field('name,sex')//直接字符串 //-> field(['name,sex'])//直接數(shù)組作為參數(shù) -> field(['name'=>'姓名','sex'=>'性別'])//中文別名有問(wèn)題,在mysql.php中的149行加入了\x7f-\xff -> where('id',3) ->find(); dump($res); } public function select() { //查詢多條記錄 $res = Db::table('user') -> field('id,name,sex,age') //-> where('age','>','50')//年齡大于50 -> where('age','between','30,45')//年齡在30與45之間 ->order('age','DESC')//排序 ->select(); echo '年齡30與45歲之間的人員有:'.'<br>'; dump($res); } public function insert() { $data = [ 'name' => '張三', 'sex' => 0, 'age' => 78, 'email' => 'zhangsan@126.com', 'password' => '123456', 'status' => 1, 'create_time' => time() ]; $num = Db::table('user') ->insert($data);//返回值為一個(gè)數(shù)值,表示添加一條成功記錄 $id = Db::getLastInsID();//最后添加記錄的ID //return $num ? '添加'.$num.'條記錄成功,id='.$id : '沒(méi)有記錄被添加'; //insertGetId()方法代替 insert()和getLastInsID() //$id = Db::table('user')->insertGetId($data); //return $id ? '添加成功,id='.$id : '沒(méi)有記錄被添加'; //推薦使用data(),不要在最后的insert中使用參數(shù) //插入多條記錄inertAll() $data = [ ['name' => '楊過(guò)','sex' => 0,'age' => 31,'email' => 'yangguo1@123.com','password' => '123','status' => 1,'create_time' => time()], ['name' => '楊過(guò)2','sex' => 0,'age' => 31,'email' => 'yangguo2@123.com','password' => '123','status' => 1,'create_time' => time()], ['name' => '楊過(guò)3','sex' => 0,'age' => 32,'email' => 'yangguo3@123.com','password' => '123','status' => 1,'create_time' => time()] ]; $num = Db::table('user') -> data($data) ->insertAll(); return $num ? '添加成功'.$num .'條記錄':'沒(méi)有記錄添加成功'; } public function update() { //更新數(shù)據(jù)必須有前置條件 $num = Db::table('user') -> update(['sex'=>1,'id' =>1]);//id為1的記錄修改性別的1女。 //return $num ? '更新成功':'更新失敗'; //Db::raw()引用原始數(shù)據(jù) $num = Db::table('user') -> where('id','=','5') -> data('age',Db::raw('age+10')) //Db::raw中使用的是字符串,要加入''. ->update(); return $num ? '更新成功':'更新失敗'; } public function delete() { //刪除不允許無(wú)條件刪除 // $num = Db::table('user')->delete(1); 岀除主鍵為1的記錄 // $num = Db::table('user')->delete([12,10]);//多個(gè)主鍵使用數(shù)組傳入 $num = Db::table('user')->where('age','=',78)->delete(); //刪除全部記錄delete()方法傳入true: delete(true) //$num = Db::table('user')->delete(true); return $num ? '刪除成功'.$num.'條記錄' : '沒(méi)有記錄被刪除'; } } ?>
添削の先生:天蓬老師添削時(shí)間:2019-06-13 17:06:26
先生のまとめ:現(xiàn)在新版中, 已不再支持中文別名, 如果支持要用, 請(qǐng)注意編碼