-1

I am having a problem, which I hope someone could help me with.

I am using CodeIgniter to pull results from a database, and I would like to add these results together. I am not much of a PHP developer, so I am not too sure where to start.

This is the function I am using;

function get_warranty($id) {
    $this->db->select('warranty');
    $this->db->where('sID', $id);
    $query = $this->db->get('cars');
    return $query->result();
}

This function, returns this;

[warranty] = Array
(
    [0] => stdClass Object
        (
                [warranty] => 2
            )

    [1] => stdClass Object
        (
                [warranty] => 5000
            )

)

But, I would like it to return this;

[warranty] = 5002;

So, it simply adds up each result it finds.

Any help at all, would be greatly appreciated, as I say, I'm not much of a PHP developer, so I don't even know where to start.

Thanks in advance!

0

2 Answers 2

0

The $query -> result() function returns an array of objects with query results... See documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

This is the modified function I propose, which simply returns an integer with the total sum, as you need:

function get_warranty($id) {

    // Query composition
    $this->db->select('warranty');
    $this->db->where('sID', $id);
    $query = $this->db->get('cars');

    // Iterate through the returned objects and accumulation in $warranty 
    foreach ($query->result() as $row) {
        $warranty += $row->warranty;
    }

    return $warranty;
}

Kind regards.

0
0

In place of return $query->result(); use return $query->result_array();. You will get returned with pure array.

Now you can use foreach loop to add the values up like this:

$add_up = 0;
foreach ($reulst_array as $values)
{
    $addup = $add_up + $values;
}

This way variable $add_up will contain the added array.

1
  • Hi Butterfruit, thanks for your (very fast) reply, but unfortunately, I got errors with this; "Unsupported operand types", is this because $values is an array? Commented Jan 22, 2014 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.