Reputation: 470
I have following model function:
function getdata_naoh($datetest2) {
$result = $this->db1->query("select round(avg(cast(t_dtl.hasil_m as decimal(6,4))),4) as hasil_m from t_hdr JOIN t_dtl ON t_hdr.headerid = t_dtl.headerid where id_solvent ='NaOH' AND status='ok' AND concentrate='0.0100' AND date_start <='$datetest2' AND date_finish >='$datetest2'");
if($result->num_rows()>0) {
return $result->result_array();
}else {
return array();
}
}
And a controller function:
function get_NaOH() {
$date_analysis = trim($this->input->post('date_analysis'));
$datetest = trim($this->input->post('date_analysis'));
$datetest2 = substr($datetest,6,4).'-'.substr($datetest,3,2).'-'.substr($datetest,0,2);
$dtnaoh = $this->M_tambahan->getdata_naoh($datetest2);
$data1 = 0;
foreach($dtnaoh as $row) {
$data1 = $row['hasil_m'];
}
$data = $data1;
echo $data;
}
The query result would be like:
| hasil_m |
| ----------- |
| 0.0100 |
I want to get hasil_m
column, according to the controller function, i set variable data1 = 0
then in foreach statement change the value as a result from hasil_m
but when i echo variable $data
i still getting data1
value = 0, did i miss something ?
Any help would be appreciated greatly, thank you.
Upvotes: 0
Views: 692
Reputation: 13128
In your loop, you're overwriting the variable with the new value. If you want to sum all of the hasil_m
data into $data1
then simply modify your foreach
loop as the following:
foreach($dtnaoh as $row) {
$data1 += $row['hasil_m'];
}
For debugging purposes, could you update your question to show exactly what the query returns?
Seems you've got float
's! You'll need to harness floatval()
in your loop to pass the values through:
foreach($dtnaoh as $row) {
$data1 += floatval($row['hasil_m']);
}
This happens because your initial variable ($data1
) is treated as a string. Meaning it doesn't and won't show the float values, treating it as a whole number.
Upvotes: 1