user1547410
user1547410

Reputation: 893

Dynamic form and looping through form array to insert into Mysql

I have a form that is built dynamically:

foreach($xml->config->popup as $popup_item){
    <input class="fm-req" id="fm-popup_name[]" name="fm-popup_name[]" type="text"  value="" />
    <textarea class="fm-req" rows="4" cols="50" id="fm-popup_desc[]" name="fm-popup_desc[]" /></textarea>
    <input class="fm-req" id="fm-popup_image[]" name="fm-popup_image[]" type="file" />
}

I haven't worked with arrays in form names before but i seen on another post on stack overflow you could do this and it seems like this is a much better way than i had planned, which was to add $i to the end of the name and increment each loop so i would have ended up with:

fm-popup_name1
fm-popup_name2
fm-popup_name3 etc etc

I could then do a loop count when building the form, pass the count as a hidden field and then use a for loop where x <= count and do my insert that way. But in the interest of improving the code and keeping it more compact and easy to understand, i think its worth doing this way but i cant figure out a good way to do it:

foreach($_POST['fm-popup_name'] as $index => $value) {
// get the value of name
}   

foreach($_POST['fm-popup_desc'] as $index => $value) {
    // get the value of name
}

foreach($_POST['fm-popup_image'] as $index => $value) {
    // get the value of name
}  

With that i can access all the data i need but i don't want to make 3 separate inserts for 1 record.

How can i take the information above and something like:

foreach($_POST['fm-popup_name,fm-popup_desc,fm-popup_image'] as $index => $value) {

INSERT INTO mytable(
    popup_name, 
    popup_desc,
    popup_image
)
VALUES(
'$popup_name',
'$popup_desc'
'$popup_image'
    )";

}

Any ideas? Hopefully code is ok, i filtered out all the other crap that is irrelevant so hopefully all the id's etc match but im just looking for a rough example and i can convert back to my code.

Upvotes: 0

Views: 700

Answers (1)

crafter
crafter

Reputation: 6296

You can use something the following, but there is a risk (can you spot it?) :

$entries = count($_POST['fm-popup_name']);
for($i = 0; $i < entries; ++$i) {
   $name = $_POST['fm-popup_name'];
   $desc = $_POST['fm-popup_desc'];

   // other processing

}

If you haven't spotted it, the risk is that not all array elements may be populated, so you may not get a proper mapping for each row, unless you enforce it on the front end and validate this before processing your loop.

Upvotes: 1

Related Questions