Welcome Guest, Not a member yet? Register   Sign In
Insert Bidimensional Array Into database
#1

[eluser]Juan Velandia[/eluser]
Hello everyone, I have this array created into a controller

Code:
Array
(
    [0] => Array
        (
            [requisito] => 1
            [tramite] => 1
        )

    [1] => Array
        (
            [requisito] => 2
            [tramite] => 1
        )

    [2] => Array
        (
            [requisito] => 3
            [tramite] => 6
        )

    [3] => Array
        (
            [requisito] => 4
            [tramite] => 3
        )

)

And in need to insert it into a table with an sql sentence like this:

Code:
insert into requisito_tramite (id_requisito, id_tramite) Values (1,1);
insert into requisito_tramite (id_requisito, id_tramite) Values (2,1);
insert into requisito_tramite (id_requisito, id_tramite) Values (3,6);
insert into requisito_tramite (id_requisito, id_tramite) Values (4,3);

I would like to pass the array data to a model and make it work, but I dont seem to get it. Could you please give an Idea or point me to a previous tread?. Thanks in advance
#2

[eluser]egy_programozo[/eluser]
Hope this is what you wanted
Code:
class Requisito_tramite extends CI_Model {

function __construct()
{
  // Call the Model constructor
  parent::__construct();
}

function insert( $args ){
  if ( is_array( $args) ) foreach( $args as $arg ){
   $this->db->insert( 'requisito_tramite', $this->param_to_col( $arg ) );
  }
}

// Replace array indexes to database table cols
function param_to_col( $args ){
  $out = array();
  if ( is_array($args) ) foreach( $args as $key => $value ){
   if ( $key == 'requisito' ) $out['id_requisito'] = $value;
   elseif ( $key == 'tramite' ) $out['id_tramite'] = $value;
  }
  return $out;
}

}
#3

[eluser]CroNiX[/eluser]
That is very wasteful. You can do this in a single query using insert_batch().

Code:
$this->db->insert_batch('tablename', $your_array_from_above);
#4

[eluser]Juan Velandia[/eluser]
Thanks to both of you. The insert_batch() worked like a charm. Thanks a lot!




Theme © iAndrew 2016 - Forum software by © MyBB