سؤال

What's the ideal way to handle an input form with multiple values, without going through each $POST_['inputname'] individually?

For example, let's say I have an invite form like this:

<form id="input-form" action="" method="post" >

   <input id="email_1" name="email_1" />
   <input  id="role_1"  name="role_1" />

   <input id="email_2" name="email_2" />
   <input  id="role_2"  name="role_2" />

   <input id="email_3"  name="email_3" />
   <input  id="role_3"  name="role_3" />

</form>

Ideally, I'd like to create two arrays with the data, one for the email addresses and another for the roles

The resulting arrays would look like this:

$emailArray = array(
   'email1' => "emailOneData", 
   'email2' => "emaiTwoData",
   'email3' => "emaiThreeData",
);
$RoleArray = array(
   'role1' => "roleOneData", 
   'role2' => "roleTwoData",
   'role3' => "roleThreeData",
);

Not sure what the best way of splitting the data is though. Also I don't really want to do something like this:

$_POST['email_1']
$_POST['email_2']
$_POST['email_3']
.....
هل كانت مفيدة؟

المحلول

Use instead an $_POST Array.

   <form id="input-form" action="" method="post" >

   <input id="email_1" name="email[]" />
   <input  id="role_1"  name="role[]" />

   <input id="email_2" name="email[]" />
   <input  id="role_2"  name="role[]" />

   <input id="email_3"  name="email[]" />
   <input  id="role_3"  name="role[]" />

</form>

After this you got an array like this:

echo'<pre>';
print_r($_POST['email']);
print_r($_POST['role']);
echo'</pre>';

Of course you still have to escape your input in dependency of your use.

After this you can use a normal foreach on the array.

$mails=array();
$count=count($_POST['role']);
for($i=0;$i<$count;$i++){
   $mails["email_".$i]=$_POST['role'][$i];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top