phpcodeignitermaxquery-builderresultset

How to return a flat array from a query built using CodeIgniter's select_max()


I am trying to get the max value from a database table via this CodeIgniter query:

$this->db->select_max('product_id');
$this->db->from('products');
$query = $this->db->get();
return $query->result();

But when I add this array of objects to to my next query, I get an error:

$this->db->insert('images', $product_id);

It show this error:

Error Number: 1054

Unknown column 'Array' in 'field list'

INSERT INTO images (product_id) VALUES (Array)

Filename: C:\wamp\www\system\database\DB_driver.php

Line Number: 330

When I did var_dump(), it showed:

array(1) {
    ["product_id"]=> array(1) {
        [0]=> object(stdClass)#21 (1) {
            ["product_id"]=> string(2) "26"
        }
    }
}

Solution

  • You are applying an array within input here's I have updated your code

    Model Code

    $this->db->select_max('product_id');
    $this->db->from('products');
    $query=$this->db->get();
    return $query->result_array();
    

    Controller Code

    $product_id = $this->Product_area_model->get_product_id();
    $data['product_id'] = $product_id[0]['product_id'];
    $result = $this->your_model->foo($data);
    

    Model Code

    function foo($data = ''){
       $this->db->insert('images',$data);
       return $this->db->insert_id();
    }