gekkogurru
gekkogurru

Reputation: 171

PHP Get name value from submit button

I have searched for a solution to this problem, the closest I came was this answer, however it does not provide sufficient explanation.

The following button contains BOTH a tournaments name and a tournaments number.

<input type="submit" name="<?php echo $tournament.$weekNumber ?>" />

Tournaments can VARY i.e. have different names & round numbers. When the button is clicked and the form is submitted how do you get the tournament name and round number contained in the button name?

I have tried

foreach($_POST as $name => $content) { //echo "The TOURNAMENT NAME IS: $name <br>"; $tournament = $name; }

The problem...it gives me the round number AND tournament name concatenated....

I could use substr() to separate the tournament and round but it wont work since tournament names and round numbers can vary...

I need BOTH the tournament name and Week Number which is concatenated in the buttons name name="<?php echo $tournament.$weekNumber ?>"

Upvotes: 1

Views: 2386

Answers (4)

Sandeep Sherpur
Sandeep Sherpur

Reputation: 2802

why you don't use hidden value.

<input type="hidden" name="tournament" value="<?php echo $tournament ?>" />
<input type="hidden" name="weekNumber " value="<?php echo $weekNumber ?>" />

<input type="submit" name="<?php echo $tournament.$weekNumber ?>"  />

now you can get both value.

Upvotes: 1

apokryfos
apokryfos

Reputation: 40683

Why not do this:

<input type="submit" name="tournament[<?php echo $tournament ?>][<?php $weekNumber ?>]"  />

and then

if (isset($_POST["tournament"]) {
foreach ($_POST["tournament"] as $tournament => $weeks) {
       foreach ($weeks as $round=> $value) {
             //Do stuff
       }
}

Upvotes: 1

Federico
Federico

Reputation: 1251

Try this: Separate the name with asymbol and then split.

<input type="submit" name="<?php echo $tournament.'_'.$weekNumber ?>"  />

foreach($_POST as $name => $content) {
        //echo "The TOURNAMENT NAME IS: $name <br>";
        list($tournament, $round) = explode('_', $name);
    }

Upvotes: 2

Blaatpraat
Blaatpraat

Reputation: 2849

When you concatenate both variables, you can add an unique string that you can use for splitting.

For example

<input type="submit" name="<?php echo $tournament.'|-|'.$weekNumber ?>"  />

In the PHP code, you can do this:

foreach($_POST as $name => $content) {
    //echo "The TOURNAMENT NAME IS: $name <br>";
    list ($tournament, $weekNumber) = explode('|-|', $name);
}

Upvotes: 2

Related Questions