By returning a row_array(), you are only going to return a single row. For example:
get_user(user_id)
That would return a single result - the user I am looking for.
Try using:
return $query->result();
Check out Generating Query Results.
Question
I'm starting with codeigniter and I have a trouble with a DB query. If I run the query in a standard PHP code, it show all data passed in the query but if I run the query using codeigniter, it show only one row with a foreach.
In the Model:
$query = $this->db->query('select C.display_name AS "Servicio", B.output AS "Status", B.last_time_ok AS "Ultimo OK" , B.last_time_critical AS "Ultimo Critical"
from system_hosts AS A
INNER JOIN system_services AS C ON C.host_object_id = A.host_object_id
INNER JOIN system_servicestatus AS B ON B.service_object_id = C.service_object_id
WHERE A.alias = "'.$hostname.'" GROUP BY C.display_name;');
return $query->row_array();
In the view:
<?php foreach ($hosts_service as $services):
?> <tr>
<h2><td><?php echo $hosts_service['Servicio'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Status'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Ultimo OK'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Ultimo Critical'] ?></a></td></h2> </tr>
<?php endforeach ?>
In Controller:
$data['hosts_service'] = $this->news_model->get_service($hostname);
It return the same value 4 times, but if I run in normal PHP it return the 3 different values containing in the DB, so the query is correct. ( I tried the same query in Toad and the result are OK).
¿What can be the problem?
Thanks a lot!
Solution
By returning a row_array(), you are only going to return a single row. For example:
get_user(user_id)
That would return a single result - the user I am looking for.
Try using:
return $query->result();
Check out Generating Query Results.
OTHER TIPS
You should use result_array()
instead of row_array()
try
return $query->result_array();
instead of
return $query->row_array();
See more info here
In addition to Nouphal.M's answer, you also need to use the item variable in the loop instead of the array variable.
<?php foreach ($hosts_service as $services): ?>
<tr>
<h2><td><?php echo $services['Servicio'] ?></a></td></h2>
<h2><td><?php echo $services['Status'] ?></a></td></h2>
<h2><td><?php echo $services['Ultimo OK'] ?></a></td></h2>
<h2><td><?php echo $services['Ultimo Critical'] ?></a></td></h2>
</tr>
<?php endforeach ?>
There's also some unrelated issues with your html. <h2>
tags should be inside the <td>
tags. You have a closing <a>
tag, but no opening <a>
tag.