Jump to content

looping arrays/post data


Recommended Posts

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();
//}
}

 

Link to post
Share on other sites

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]" >

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.