0

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

我的桌子有“ id, description, date_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'];
    }
4

3 回答 3

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
}

但是,请确保echo结果在 中view,希望您这样做,另外,不要忘记加载model.

于 2013-09-19T03:56:49.443 回答
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;
}
于 2013-09-19T04:01:54.537 回答
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
    }

现在它会正常工作

于 2013-09-19T03:55:36.103 回答