1

so I am trying to do something in php based on what button a user presses in the html form.

<?php
if (isset($_POST["submit"])) {
echo "do this";
}else{
echo "do this instead";
}
?>



<form action ="Deliveryslot.php" method="post">

    <span class="em">
    <button type="submit" name = "em" value="1" > <img src="em.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "ea" value="2" > <img src="ea.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "la" value="3" > <img src="la.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "e" value="4" > <img src="e.png"  /></button>
    </span>
    <span class="em">
    <button type="submit" name = "ln" value="5" > <img src="ln.png" /></button>
    </span>
</form>

How can I get the if statement at the top to respond to the values 1,2,3, etc..? So far I can't figure out why the submit function is not working in this code! I am showing it this way because I know this syntax is supposed to be correct and I am asking how I can change it to validate on the values.

Sukhi Kaur
  • 84
  • 6

2 Answers2

2

To make it easier, you really don't need to capture each name. Put them in the same name instead. Like this:

<form action ="" method="post">
    <span class="em">
    <button type="submit" name = "submit[em]" value="1" > <img src="em.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "submit[ea]" value="2" > <img src="ea.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "submit[la]" value="3" > <img src="la.png" /></button>
    </span>
    <span class="em">
    <button type="submit" name = "submit[e]" value="4" > <img src="e.png"  /></button>
    </span>
    <span class="em">
    <button type="submit" name = "submit[ln]" value="5" > <img src="ln.png" /></button>
    </span>
</form>

Then on your PHP:

<?php
if (isset($_POST["submit"])) {
    $submit = $_POST['submit'];
    $key = key($submit); // these get the em, ea, la, e, ln
    $value = $submit[$key]; // and then use that key to get the value
    echo "$key => $value"; // em => 1, ea => 2, la => 3, e => 4, ln => 5
}
?>
Kevin
  • 41,694
  • 12
  • 53
  • 70
1

In PHP you get elements by name and you access them by $_POST["elementNameHere"]. So in your code to access the buttons values you do this:

if (isset($_POST["em"])) { // Check that a element with name "em" exist
    $btn1 = $_POST["em"]; // $btn1 = 1
    $btn2 = $_POST["ea"]; // $btn1 = 2
    ...
}
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54