Search code examples
codeignitermultiple-forms

codeigniter multiple field submit with a single form and button


I have multiple forms which will be generated 4 times with the same field with a loop. And I am confused about how to submit these fields in the same database table with a loop.

my form looks like this:

<form action="http://localhost/pages/edit" method="post" name="form">
<p><label for='short'>Name</label><br/><input type="text" name="title[]" value=""  /></p>
    <p><label for='short'>Url</label><br/><input type="text" name="url[]" value="ddd-df-adsfasd--asdf"  /></p>
    <p><label for='short'>Short Description</label><br/><textarea name="shortdesc[]" cols="90" rows="12" id="short" size="40" ></textarea></p>
    <p><label for='long'>Long Description</label><br/><textarea name="longdesc[]" cols="40" rows="5" id="long" ></textarea></p> 
        <input type="hidden" name="category_id[]" value="124" />
<input type="submit" name="submit" value="Update"  />
</form>

This form contents will be generated 4 times. And I am confused about how to take these values to the controller and add then to database.


Solution

  • Give this a try:

    $fields = array('title', 'url', 'shortdesc', 'longdesc', 'category_id');
    
    foreach ($fields as $field)
    {
        foreach ($_POST[$field] as $key => $value)
        {
            $data[$key][$field] = $value;
        }
    }
    
    foreach ($data as $values)
    {
        $this->db->insert('table_name', $values);
    }
    

    There's surely easier ways to do it, but this is the most flexible with the form field names that you are using, and doesn't care how many different items you post. You did say you were inserting, not updating, and this assumes your table column names match your form field names.

    You could just loop through the $_POST array, but this will allow you to easily post other fields without adding their values to the array for the insert.

    When you said i have multiple form, I was a little unclear: You need to make sure it's all in one <form> tag.