Shah
Shah

Reputation: 21

How to dynamically create buttons names and detect which button is pressed in PHP?

This is an experiment int PHP that I'm currently working on. It'll be part of a bigger file. The idea is, the program will generate a set of submit buttons in a form and a unique name will be assigned to each button in this convention: btn[the order of button]

The page will then poll to find if any button was pressed using isset(). Here's what I've got so far.

<html>
<head>
    <title>Test Dynamic Naming</title>
</head>

<body>
    <form action="testDynamicNaming.php" method="POST">
        <?php
            $row = 9;

            for($i = 0; $i < $row; $i++) {
                $name = 'btn['.$i.']';

                ?>
                    <input type="submit" name="<?php echo $name; ?>" value="<?php echo $name; ?>"/>
                <?php

                echo "<br>";
            }
        ?>
    </form>

    <?php
        extract($_REQUEST);

        for($i = 0; $i < $row; $i++) {
            $name = 'btn['.$i.']';

            if(isset($_POST[$name])) {
                echo "<br><br>".$name.' is pressed.';
            }

            // OR

            if(isset($$name)) {
                echo "<br><br>".$name.' is pressed.';
            }
        }
    ?>
</body>
</html>

I managed to set the name and values of the button as I wanted but the page couldn't detect the button that was pressed. What am I missing here, or is there any other way that I could accomplish the same task?

Upvotes: 0

Views: 1325

Answers (3)

Pavel
Pavel

Reputation: 250

Maybe use javascript?

easy e.g.

     <input type="submit" name="<?php echo $name; ?>" onclick="document.getElementById('<?php echo $name; ?>_pressed').value='true';" value="1"/>
     <input type="hidden" id="<?php echo $name; ?>_pressed" name="x1_pressed" value="false"> 

if(isset($_POST[$name]) == "true") {

Upvotes: 1

Jompper
Jompper

Reputation: 1402

if(isset($_POST['btn'])){
  foreach($_POST['btn'] as $key => $value){
    echo "Button {$key}:{$value} pressed";
  }
}

Upvotes: 2

Manish Jangir
Manish Jangir

Reputation: 5437

you may use

if(isset($_POST['btn'][$i])) {
            echo "<br><br>".$_POST['btn'][$i].' is pressed.';
        }

Upvotes: 1

Related Questions