Jason
Jason

Reputation: 1613

Catch a dynamic variable by using POST

I write two file main.php and download.php.

main.php

echo"<form action='download.php' method='post'>"
for(i = 0; i < 10; i++){
    echo"<input type='submit' name='$i'>";
}

In download.php, I want to know which name's button is pressed? (from 1 to 10 to download the file), so that I can use it in download.php to download file.

I have tried to use $_POST["$i"] but failed.

What if the $i is a random filename?

Thx!

complete code

main.php:http://codepad.org/4zXPhqFy

Upvotes: 1

Views: 106

Answers (3)

Marcio Mazzucato
Marcio Mazzucato

Reputation: 9295

Firstly you should to start the submit's names with letters, not digits. And if you want buttons from 1 to 10 your $imust start with 1, not 0.

Try do to this:

main.php

echo '<form action="download.php" method="post">';

for( $i = 1; $i <= 10; $i++){
    echo '<input type="submit" name="button[' . $i . ']" value="Send" />';
}

echo ''

download.php

if( isset($_POST['button']) )
{
    $button = key($_POST['button']);

    echo 'Button ' . $button . ' was clicked';
}

Upvotes: 1

Kris
Kris

Reputation: 6112

Here is another solution

build the buttons

for( $i = 1; $i <= 10; $i++){
  echo '<input type="submit" name="button[' .  chr($i+64) . ']"/>';
}

I did the chr so that you can see it can be any text

Find out which was pressed

echo 'button ' . key($_POST['button']) . ' was pressed';

The advantage of this way, is you do not need a loop to find out the button that was pressed

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270617

Access $_POST via $key => $value in a loop. Exclude other values you know the names of (if you have others).

foreach ($_POST as $key => $value) {
  // Look for form keys not among other known ones
  if (!in_array($key, array('other','known','input','names')) {
    echo "You clicked $key";
  }
}

Or, use ctype_digit() on the post key to determine if it is numeric, excluding any other string keys you may have in there.

foreach ($_POST as $key => $val) {
  if (ctype_digit($key)) {
    echo "You clicked $key";
    // Access it via $_POST[$key]
  }
}

Note that unless you are using HTML5, name attributes must begin with a letter, not a number. If you are using HTML5, anything but an empty string is allowable in the name.

Upvotes: 1

Related Questions