我无法在CodeIgniter中显示查询结果

时间:2013-09-19 03:48:53

标签: php codeigniter

我无法将我的查询从数据库显示到CodeIgniter。

我的表格中有“iddescriptiondate_stamp”。我只想获得date_stamp

这是我的代码:

模型

public function get_holidays()
{
    $this->db->select('date_stamp');
    $this->db->from('holidays');
    $query = $this->db->get();

    if($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
            $data[] = $query->row();
        }
    }
    else
    {
        $data = "";
    }
    return $data;
}

控制器:

    $holidays = $this->emp->get_holidays();
    //the result should be like this
    //$holidays=array("2013-09-20","2013-09-23", "2013-09-25");
    foreach($holidays as $holiday){
        // 
         echo $holiday['date_stamp'];
    }

3 个答案:

答案 0 :(得分:1)

在您的代码中,foreach ($query->result() as $row)循环

$data[] = $query->row();

应该是

$data[] = $row;

或者,只是从模型中返回结果return $query->result()并在控制器中执行循环,因为您再次执行相同的操作。因此,您可以使用model代替

if($query->num_rows() > 0)
{
    return $query->result();
}
return false;

然后,在controller你可以做

$holidays = $this->emp->get_holidays();
if($holidays) {
    // do the loop or whatever you want
}

但是,请务必在echoview结果,希望您这样做,同时,不要忘记加载model

答案 1 :(得分:1)

我通常在视图中打印模型中的值,而控制器是我浏览页面的位置。嗯,在模型中:

public function get_holidays()
{
    $this->db->select('date_stamp');
    $this->db->from('holidays');
    return $this->db->get();
}

并在视野中:

$this->load->model('holiday_model');
$holidays = $this->holiday_model->get_holidays();

foreach( $holidays->result AS $items ) 
{
    echo $item->date_stamp;
}

答案 2 :(得分:0)

更新模型

  public function get_holidays()
  {
    $data = array();
    $this->db->select('date_stamp');
    $this->db->from('holidays');
     $query = $this->db->get();

if($query->num_rows() > 0)
{
    foreach ($query->result() as $row)
    {

        $data[]=$row->date_stamp; //changed here
       // array_push($data, $row->date_stamp); 

    }
}
else
{
    $data = array();
}
return $data;
}

更新控制器

    $this->load->model('holiday_model');

    $holidays = $this->emp->get_holidays();
    //the result should be like this
    //$holidays=array("2013-09-20","2013-09-23", "2013-09-25");


    if($holidays) { //checking $holiday 
      foreach($holidays as $holiday){
         echo $holiday; //changed here
     }
    } else {
        echo 'No Holiday Found; //changed here
    }

现在它可以正常工作