简体   繁体   中英

dynamically selecting all variables with the same prefix in php

I have a form and there is a button to append another set of input boxes if you wish to add more information. Everytime it adds a new set of boxes all the input boxes get a unqiue number added on for that set of input boxes.

Example:

If you have three sets of input boxes it would look like this:

name, age, gender, dob

name1, age1, gender1, dob1

name2, age2, gender2, dob2

However, when I send this information over to my php file I extract the information from the array so each one is a variable. So, name would be $name and name1 would be $name1 and so on. But my question is how can I sanitize and validate all the names at once and all the ages at once etc..

The reason I am asking is because I have googled this alot and I can't find an answer on how to do this.

Try to create sets as given in sample below:

For first set:

<input type="text" name="name[]" id="name1" />
<input type="text" name="gender[]" id="gender1" />
<input type="text" name="age[]" id="age1" />
<input type="text" name="dob[]" id="dob1" />

For second set:

<input type="text" name="name[]" id="name2" />
<input type="text" name="gender[]" id="gender2" />
<input type="text" name="age[]" id="age2" />
<input type="text" name="dob[]" id="dob2" />

and set all the further sets accordingly.

Now, to get posted data you can use

<?php
echo "<pre>".print_r($_POST, true)."</pre>";
?>

You may use something like this for each entity:

<input type="text" name="age[]" id="age1" />

Here, id should be in incremental order with JavaScript or jQuery and name should be same which will give you an array for all the attributes in $_POST or $_REQUEST

Print $_REQUEST and you will come to know how exactly you can get all the data.

You are already getting the array for the name, age, etc.

To sanitize use array_map() function in php. It will sanitize the array.

EXAMPLE

$result = array_map("stripslashes", $result);

Here $result is an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM