本文实例讲述了ThinkPHP5查询数据及处理结果的方法。分享给大家供大家参考,具体如下:
在处理数据库查询结果时遇到了些问题,记录下用到过的几种查询方式和结果处理。
1. 查询某条记录
$where=array( "version_id"=>$version_id ); $data = model("PackageWhitelist")->where($where)->find(); $this->assign("package_id",$package_id); $where=array( "package_id"=>$package_id ); $data = model("Package")->where($where)->find(); if($data){ $this->assign("target_version",$data['target_version']); }
2. 查询某条记录某个字段
$device_number_list = model("PackageWhitelist")->where($where)->field("device_number")->find();
$this->assign("device_number",$device_number_list['device_number']);
3. 查询多个记录某个字段 , 并处理结果,结果是一个数组集
$where=array( "version_id"=>$version_id ); $data = model("PackageWhitelist")->where($where)->field("device_number")->select(); $device_number_list=''; foreach($data as $val){ $list = $val->toArray(); if($device_number_list){ $device_number_list=$device_number_list.';'.$list["device_number"]; }else{ $device_number_list=$list["device_number"]; } }
4. 查询多条记录
$where=array( "version_id"=>$version_id ); $data = model("PackageWhitelist")->where($where)->select(); $device_number_list=''; foreach($data as $val){ $list = $val->toArray(); if($device_number_list){ $device_number_list=$device_number_list.';'.$list["device_number"]; }else{ $device_number_list=$list["device_number"]; } }
5. 以页形式查询,并处理结果。
public function index($version_id){ $where=array( "version_id"=>$version_id ); $version_name = model("Version")->where($where)->field("version_name")->find(); $listrows=config("LISTROWS")"LISTROWS"):10; $package_lists=model("Package")->where($where)->paginate($listrows); $package_infos = $package_lists->toArray()["data"]; foreach($package_infos as $key=>$value){ $package_infos[$key] = array("source_version" => $version_name["version_name"]) + $package_infos[$key]; } }
再来总结一下TP5的三种查询数据库方式
方式一:原生sql查询
代码示例:
<"htmlcode"><"htmlcode"><"htmlcode"><"_blank" href="https://www.jb51.net/Special/39.htm">ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。