Jump to content


This topic is now archived and is closed to further replies.


convert post variables to array

Recommended Posts

***posted this in PHP General, then realized here was a better place....sorry for the dupe...***

I'm working on a stat tracking application for my ultimate frisbee team. The 'Add Stats' form is generated dynamically based on what tournament you are working on, what game you are adding stats for, and which players attended that tournament.  Each form field has a common name (player, tgs, lgs, sgs, etc etc) followed by the players ID number to identify those stats as belonging to a specific player. so for player ID 3, the form fields would be player_3, tgs_3, sgs_3, etc etc).  There are 8 data fields per player, and there can be upwards of 20 players submitted in a form.

Instead of creating individual $_POST('....'] variables for each submitted value (which could be very tedious), is there a way to store the values for each player in a multi-dimensional array, then have the SQL Data Insertion code loop through each value in the array? I haven't done much with arrays in my programming, so I'm not real sure how to work with them.

Thanks so much!

Share this post

Link to post
Share on other sites
Use a foreach loop to automatically create the various variables:
[code]foreach($_POST as $field => $value)
  //automatically create the various variables:
  $$field = mysql_real_eascape_string($value));
Now say you have forum fields called player you use $player to access that fields values, rather than $_POST['player']

Share this post

Link to post
Share on other sites
Instead of appending the id to the field name, use id as an array index. EG

      <input type="text" name="player[1]">
      <input type="text" name="tgs[1]">
      <input type="text" name="lgs[1]">
      <input type="text" name="sgs[1]">
      <input type="text" name="player[2]">
      <input type="text" name="tgs[2]">
      <input type="text" name="lgs[2]">
      <input type="text" name="sgs[2]">
      <input type="text" name="player[3]">
      <input type="text" name="tgs[3]">
      <input type="text" name="lgs[3]">
      <input type="text" name="sgs[3]">
      <input type="submit" name="submit" value="submit">

To process

[code]foreach ($_POST['player'] as $id => $player) {
        $tgs = $_POST['tgs'][$id];
        $lgs = $_POST['lgs'][$id];
        $sgs = $_POST['sgs'][$id];
        // process player data

Share this post

Link to post
Share on other sites


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.