Jamiesw Posted April 28, 2021 Share Posted April 28, 2021 Hi there, I am wanting to insert post data into my DB, this is guest information if i do a $safePost = filter_input_array(INPUT_POST); print_r($safePost); i get the following output. Array ( [action] => addGuestInfo [guestno] => 2 [bookingid] => 151 [customerid] => 22 [Guestname-0] => Jamie [Guestname-1] => Joe [GuestAge-0] => 4-3 [GuestInfo-0] => celiac [GuestAge-1] => 18 [GuestInfo-1] => wheat ) normally the guestname-0, guestage-0, guestinfo-0 would be in correct order but we have to ensure the just incase it isns't (see output above) we cater for that aswell, we can have upto 6 guest details coming in at once. so I need to loop through the data and insert into my DB. I have tried various for / foreach loops but cant seem to get it to group the data together I have tried things like below, but it inserts each record multiple times. $safePost = filter_input_array(INPUT_POST); foreach($safePost as $key => $value){ $exp_key = explode('-', $key); // for ($i =0; $i <= $guestcount; $i++) { switch ($exp_key[0]) { case 'Guestname': $booking->guestno = $exp_key[1]; $booking->guestname = $val; break; case 'GuestAge': $booking->guestno = $exp_key[1]; $booking->guestage = $val; break; case 'GuestInfo': $booking->guestno = $exp_key[1]; $booking->guestinfo = $val; break; default: break; } //CALLS FUNCTION TO INSERT TO DB result = lastInsertId(); $result= $booking->insertGuestDetails(); //} } Quote Link to comment https://forums.phpfreaks.com/topic/312558-looping-arrayspost-data/ Share on other sites More sharing options...
Barand Posted April 28, 2021 Share Posted April 28, 2021 Instead of using hyphens, use array indices in your form input field names <input type="text" name="guestname[0]" > <input type="text" name="guestname[1]" > Quote Link to comment https://forums.phpfreaks.com/topic/312558-looping-arrayspost-data/#findComment-1586208 Share on other sites More sharing options...
Jamiesw Posted April 28, 2021 Author Share Posted April 28, 2021 Perfect thanks, code works a treat now. Quote Link to comment https://forums.phpfreaks.com/topic/312558-looping-arrayspost-data/#findComment-1586217 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.