2

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.

1
  • Your for attributes are only relevant if they relate to input fields with the same id attribute value. Because you have repeating form fields, you should append an incremented number to each for and id value because id values must be unique in a valid HTML document. Commented Feb 13 at 4:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.