I can't display my query from database to CodeIgniter.
My table has " id
, description
, date_stamp
". I just want to get only the date_stamp
.
Here is my code:
Model
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;
}
Controller:
$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'];
}
In your code, inside foreach ($query->result() as $row)
loop
$data[] = $query->row();
should be
$data[] = $row;
or, just return the result return $query->result()
from the model and do the loop in the controller, because you are again doing same thing. So, you can do in your model
instead
if($query->num_rows() > 0)
{
return $query->result();
}
return false;
Then, in your controller
you may do
$holidays = $this->emp->get_holidays();
if($holidays) {
// do the loop or whatever you want
}
But, make sure to echo
the result in view
, hope you do so, also, don't forget to load the model
.
I usually print the value from model in view while controller is where I navigate the page to. Well, in model:
public function get_holidays()
{
$this->db->select('date_stamp');
$this->db->from('holidays');
return $this->db->get();
}
and in view:
$this->load->model('holiday_model');
$holidays = $this->holiday_model->get_holidays();
foreach( $holidays->result AS $items )
{
echo $item->date_stamp;
}
Updated Model
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;
}
Updated Controller
$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
}
Now it will work fine
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.