CodeIgniter Forums
Easy way of inserting data into a table from a submitted form - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Easy way of inserting data into a table from a submitted form (/showthread.php?tid=44720)



Easy way of inserting data into a table from a submitted form - El Forum - 08-24-2011

[eluser]jvicab[/eluser]
I would like to share an elegant and easy way of inserting data into a table from a submitted form:

Here is what I do: I developed two functions for this purpose, and after that inserting is just a piece of cake.

The idea is calling a function which returns an array of all elements posted that match a table's field names. After that the second function is called which takes that array and inserts it into the table returning the id of the record just inserted.

Easy, doesn't it?

Here are the functions:

Code:
function CreateFieldArrayFromPOST($tablename)
  {
    $res = array();
    $fields = $this->db->list_fields($tablename);
    foreach($fields as $field)
    {
      $data = $this->input->post($field);
      if (!empty($data))
        $res[$field] = $data;
    }
    return $res;
  }

  function Insert($tablename)
  {                            
    $data = $this->CreateFieldArrayFromPOST(tablename);
    $this->db->insert($tablename, $data);
    return $this->db->insert_id()
  }

That's it! Just put them in a model and call Insert function with the tablename.

There is only one main warn: The name of the input tags in your html form must have the same name as their corresponding table field name!

Enjoy!