Ricky
Ricky

Reputation: 5201

php while loop variable increase number

I have a while loop that gathers information from my DB. I then echo that out like this...

$num = 1;
$i=0;
$drop = 'yes';
echo '<form id="drop_form" method="post" action="here.php">';

while( $row = mysql_fetch_assoc($query)) {

   $player[] = $row['player'];

   echo '<tr class="rows"><td>'; echo'<input type="hidden"
   name="yeah" value="'.$num.'"/>
   <input name="submit" type="submit" value="submit"/>';

   echo $player[$i].'</td></tr>'; 

   $num++;                         
   $i++;
}
echo '</table>';
echo '</form>';

when I post my $num variable it always show up as the last possible number. So if there are 7 rows in that query then the number will be 7. I want to be able to click on the submit button and get the hidden value in the submit form.

Player 
mike    hidden number = 1
chris   hidden number = 2
jim     hidden number = 3
dan     hidden number = 4

Upvotes: 1

Views: 2762

Answers (2)

Rwd
Rwd

Reputation: 35170

Add this before the start of your while loop: $player = array();

You should always define arrays before a loop :)

Hope this helps! :)

Also:

1.Change name="yeah" to name=yeah[] as you want this input to be an array. 2.Move the submit button outside of the while loop as you should only need one of these.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Your form is submitting something like yeah=1&yeah=2&yeah=3... This is equivalent to the following PHP:

$_POST['yeah'] = 1;
$_POST['yeah'] = 2;
$_POST['yeah'] = 3;

From this you can see that the variable is being overwritten.

Try using name="yeah[]", as this will result in an array, as follows:

$_POST['yeah'][] = 1;
$_POST['yeah'][] = 2;
$_POST['yeah'][] = 3;

Resulting in Array(1,2,3);

Upvotes: 1

Related Questions