abstrak:本章主要學(xué)習(xí)tp5.1的數(shù)據(jù)庫的增刪改查,通過更改config/database.php下的數(shù)據(jù)庫信息為指定的數(shù)據(jù)庫后,通過tp5.1封裝的方法進(jìn)行增刪改查,代碼如下:(為方便提交,代碼寫在index頁面)index.php:<?php namespace app\index\controller; use think\Db; use think\Reques
本章主要學(xué)習(xí)tp5.1的數(shù)據(jù)庫的增刪改查,通過更改config/database.php下的數(shù)據(jù)庫信息為指定的數(shù)據(jù)庫后,通過tp5.1封裝的方法進(jìn)行增刪改查,代碼如下:(為方便提交,代碼寫在index頁面)
index.php:
<?php namespace app\index\controller; use think\Db; use think\Request; class Index { public function index() { // 查詢構(gòu)造器執(zhí)行CURD $this->execCURD(); } public function execCURD() { //查詢單條記錄 $res=Db::table('user')->field('name,weight,height') ->where('uid','>',10) ->where('weight','between',[90,100]) ->order('weight DESC') ->find(); echo '查詢uid大于2,且胸圍在90-100,按胸部倒序的單條記錄為:'.var_export($res,true); echo '<br>'; //查詢多條記錄 $res=Db::table('user')->field('name,weight,height') ->where('height','>=',160) ->order('weight DESC') ->limit(2) ->select(); echo '查詢身高大于160,按胸部倒序的前兩條記錄為:'.var_export($res,true); echo '<br>'; //執(zhí)行單條記錄插入 $data=[ 'name'=>'武藤蘭', 'weight'=>90, 'height'=>160, 'add_time'=>time() ]; $num=Db::table('user') ->data($data) ->insert(); $id=Db::getLastInsID(); echo '執(zhí)行插入的id為:'.$id; //執(zhí)行多條記錄插入 $data=[ ['name'=>'麻美','weight'=>95,'height'=>160,'add_time'=>time()], ['name'=>'愛田由','weight'=>92,'height'=>162,'add_time'=>time()], ['name'=>'松金洋子','weight'=>96,'height'=>165,'add_time'=>time()], ]; Db::table('user')->data($data)->insertAll(); echo '<br>'; echo '執(zhí)行插入多行記錄成功'; //更新操作 $num=Db::table('user')->data(['weight'=>Db::raw('weight+2')]) ->where('weight','<',95) ->update(); echo '<br>'; echo '執(zhí)行更新,胸圍小于95的女星,胸圍增加2'.($num ? '。更新成功'.$num.'條記錄': '。沒有記錄被更新'); //刪除操作 $num=Db::table('user')->where('uid','>',40)->delete(); echo '<br>'; echo '執(zhí)行刪除uid大于48的數(shù)據(jù),'.($num ? '刪除成功'.$num.'條記錄': '沒有記錄被刪除'); } }
執(zhí)行效果圖:
Guru membetulkan:韋小寶Masa pembetulan:2019-02-21 17:20:20
Rumusan guru:寫的很不錯(cuò) 沒事的時(shí)候要記得多去練習(xí) 項(xiàng)目寫多了自然技術(shù)也就上去了