duanganleng0577 2016-09-08 17:09
浏览 32
已采纳

如何在codeigniter中处理空数组?

So these are my codes.

model

function read() {
     $sql= "SELECT * from table WHERE name = 'rabin'";
     $query = $this->db->query($sql);
     $res = $query->result_array();
     return $res;
 }

controller

function show() {
    $this->load->model("db");
    $array['data'] = $this->db->read();
    $this->load->view("page", $array);
 }

view

foreach($data as $val) {
   "<p>" . echo $val['name']; . "</p>"
   "<p>" . echo $val['address']; . "</p>"
}

Here, when there are no records in the database satisfying the WHERE clause in the query, the model returns null and I get error saying $data expects parameter 1 to be array, null given. There are several methods to deal with this situation. But, what would be the best possible way to handle this situation ?

  • 写回答

4条回答 默认 最新

  • douchu2823 2016-09-08 17:26
    关注

    In your model try out this

    function read() {
        $this->db->select()->from('table')->where('name', 'rabin');
        $sql_stmt = $this->db->get();
        return $sql_stmt->result();
    }
    

    and then to check you are getting the result - in your controller,

    function show() {
         $this->load->model("db");
         $array= array( 'data' => $this->db->read());
         $this->load->view("page", $array);
     }
    

    To view the result in your view file do print_r($data);

    And then let me know what you get / result

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录
  • ¥15 关于#Django#的问题:我的静态文件呢?
  • ¥15 关于CPLEX的问题,请专家解答
  • ¥15 cocos的点击事件 怎么穿透到 原生fragment上。
  • ¥20 基于相关估计的TDOA算法中的加权最小二乘拟合法matlab仿真
  • ¥20 基于相关估计的TDOA算法中的自适应加权广义互相关法。
  • ¥15 abaqus CAE 2024软件启动问题
  • ¥20 基于相关估计的TDOA算法中的局部互相关函数滤波matlab仿真