0

I've got quite a few variables such as $UserID and $UserName, each one have a number relating to it after, so for example $UserID1, $UserName1, $UserID2, $UserName2 and so on.

For each number I'd like to use a foreach statement to insert them in to their own rows, is this possible?

BN83
  • 902
  • 3
  • 9
  • 29

2 Answers2

0

Why not store these variables in an array and loop through them with foreach? Sure you can use variable variables to handle this, but it can get confusion if you don't keep track of everything right.

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
  • Using `foreach($_POST as $key => $value){ $$key = $value; }` how would I go about getting those in to an array to then insert? – BN83 Apr 09 '14 at 01:07
  • There's lots of ways. If you want to shove everything into its own column and the column names match up with your form field names, then you can use [array_keys()](http://www.php.net/manual/en/function.array-keys.php) and [array_values()](http://www.php.net/manual/en/function.array-values.php). You can also create 2 arrays, check if `$key` begins with **"UserName"** or **"UserID"**, and shove them in, and iterate over them later. Whatever method you choose, be sure to [sanitize your input](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php)! – Sunny Patel Apr 09 '14 at 01:29
0

Given that you know the number of variables you can do

    for($i=1, $i <= $total; $i++){
${"UserID".$i} //identical to $UserID1
}

this will dinamically generate your variable names...and you can use them in the insert...

Feras
  • 2,114
  • 3
  • 20
  • 42