In PHP how do you send data through a form without any data inputs apart from buttons?

Advertisements

Trying to find out which button the user has pressed. I want to get the value that is in the form-label when the corresponding button is pressed. Is this possible? Thanks

index.php

<html>

<form action="./process.php" method="post">

<?php 

for ($index = 1; $index <= 10; $index++) {
    echo "<br>";
    echo "<label>$index</label>";
    echo "<input type=\"submit\" value=\"Submit\">";
    echo "<br>";
}

?>

</form>

</html>

process.php

<?php 

# I want to print the number here? So if the button next to number 1 was pressed it would be 1 printed here.

?>

Thanks

>Solution :

I suspect the stumbling block here is the use of <input type="submit"> in which the examples you’ve seen so far use value="Submit" to set the text of the button.

But if you use a <button type="submit"> instead, you can set the text within the element and control its value separately:

for ($index = 1; $index <= 10; $index++) {
    echo "<br>";
    echo "<label>$index</label>";
    echo "<button type=\"submit\" name=\"myButton\" value=\"$index\">Submit</button>";
    echo "<br>";
}

Whichever button is clicked would be the only one posting its value to the server, and would be observable in $_POST['myButton'].

(As an aside… type="submit" is the default and doesn’t necessarily need to be specified explicitly, but I personally consider it good practice to be explicit in these cases because we’ve often seen bugs/confusion when no type is specified and a form submit is not the intended action, but rather some client-side handler is.)

Leave a ReplyCancel reply