Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading