Page 1 of 1

Stuck in form logic [Solved]

Posted: Tue Mar 31, 2009 1:32 am
by papa
Good morning,

I have a form which displays x amount of fights to bet on, it's a bit tacky at the moment because I can't get my head around the logic and design I should use regarding sending the data to my submit page.

The variables I need to pass I as follows:

fightId
fighterId1, betAmount
fighterId2, betAmount

The form now is just a hidden field with fightId and a text input field for betting amount.

So if betAmount for that fightId is set, it should add that bet to the db, and if not it should just ignore that fight.

What I've done now is to have a radio button next to the input text field just to be able to pass the variables I need, but that feels redundant and not very user friendly.

Removing the radio button, the form is as follows:

Code: Select all

 
<input type='hidden' name='fightId[]' value='4' />
<input type="text" name="bet4[4]" value=""  class='text'  id='bet4[4]' />
<input type="text" name="bet4[3]" value=""  class='text'  id='bet4[3]' />
 
bet4[4] is bet for fightId 4 and fighterId 4, value is what the user is betting.
bet4[3] is bet for fightId 4 and fighterId 3, value is what the user is betting.

Then on the submit page I loop through the fightId array:

Code: Select all

 
foreach($_POST['fightId'] as $id) {
   if(isset($_POST['bet'.$id])) {
   }
}
 
What's an easy way to retrieve the key for that array, check that only one of the fighters have been bet on?

I need to store the key in order to be able to insert fightId, fighterId, betAmount to the DB table.

Re: Stuck in form logic

Posted: Tue Mar 31, 2009 2:06 am
by requinix
You can use a 2d array if you want, make things easier...

Code: Select all

<input type='hidden' name='fightId[0]' value='4' />
<input type="text" name="bet[0][4]" value=""  class='text'  id='bet_0_4' />
<input type="text" name="bet[0][3]" value=""  class='text'  id='bet_0_3' />
(Last I knew, [ and ] are not allowed in the id.)

Code: Select all

foreach($_POST['fightId'] as $id => $fightId) {
   if(!empty($_POST['bet'][$id])) {
      foreach ($_POST['bet'][$id] as $fighterId => $bet) {
         // $id is which fight (on the page, if you have more than one) - not the fight ID
         // $fightId is the fight ID
         // $fighterId is the fighter ID
         // $bet is the bet amount
      }
   }
}
(isset will return true simply because it exists - empty will check for a value too)

Re: Stuck in form logic

Posted: Tue Mar 31, 2009 4:01 am
by papa
Thank you very much!