1

I have some repetitive form field variables and want to put them into variable after POST.

$item_code1 = mysql_sanitize( $_POST['item_code1'] );
$units1 = mysql_sanitize( $_POST['units1'] );
$qty1 = mysql_sanitize( $_POST['qty1'] );
$size1 = mysql_sanitize( $_POST['size1'] );
$make1 = mysql_sanitize( $_POST['make1'] );
$finish1 = mysql_sanitize( $_POST['finish1'] );

$item_code2 = mysql_sanitize( $_POST['item_code2'] );
$units2 = mysql_sanitize( $_POST['units2'] );
$qty2 = mysql_sanitize( $_POST['qty2'] );
...

These set of form variables can be 1 - 10 (or more) I am passing how many sets of these form variables through a counter

$ctr_i = mysql_sanitize( $_POST['ctr_i'] );

How do i get the variables like above programatically ? i mean looping through $ctr_i, i want to put all the POST values to PHP variables.

Any ideas?

2
  • You can create an array of element maybe. Commented Feb 2, 2013 at 10:09
  • 2
    have you extract() function? tried php.net/manual/en/function.extract.php Commented Feb 2, 2013 at 10:10

3 Answers 3

2
<?php
foeach($_POST as $key => $val){
 $$key = mysql_sanitize($val);
}
?>
Sign up to request clarification or add additional context in comments.

4 Comments

But what if the first letter of $key is a number?
The variable name can't start with a number so what happens when $$key is created when first letter of $key is a number (0-9)
@SandyLee_user53167: then my answer will be incorrect, but who use numbers?
umm.. mysql_sanitize fails on some array fields i have.. any sol??
2

You can try something like the below:

$post = $_POST;
$post = array_map('mysql_sanitize', $post);
extract($post);

After this you will have set of the variables.

Comments

2

It would be easier if you have input arrays in your html page like

<input type="text" name="field[]" />
<input type="text" name="field[]" />
<input type="text" name="field[]" />

Then you can collect all the values on the php side by

$field = $_POST['field'];

foreach($field as $a_field)
{
  echo $a_field;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.