在PHP中,如何通过表单发送数据,除了按钮之外没有任何数据输入?[已关闭]

7d7tgy0s  于 12个月前  发布在  PHP
关注(0)|答案(2)|浏览(119)

已关闭,此问题需要更focused。它目前不接受回答。
**想改善这个问题吗?**更新问题,使其只关注editing this post的一个问题。

2天前关闭。
Improve this question
试图找出用户按下了哪个按钮。我想得到的值是在表单标签时,相应的按钮被按下。这可能吗?谢谢
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.

?>

谢谢

c3frrgcw

c3frrgcw1#

我怀疑这里的绊脚石是<input type="submit">的使用,到目前为止,您看到的示例使用value="Submit"来设置按钮的 text
但是如果你使用<button type="submit">,你可以在元素中设置文本并单独控制它的值:

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

单击的按钮将是唯一一个将其值发送到服务器的按钮,并且在$_POST['myButton']中可以观察到。
(As旁白type="submit"是默认值,不需要显式指定,但我个人认为在这些情况下显式指定是一种好的做法,因为我们经常看到错误/混乱,当没有指定类型时,表单提交不是预期的操作,而是一些客户端处理程序。

vwkv1x7d

vwkv1x7d2#

您需要为每个提交按钮添加一个自定义名称。

<?php 

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

?>

你可以检查哪个按钮已经提交(并获取它们的值):

for ($index = 1; $index <= 10; $index++) {
    if (isset($_POST['submit_'.$index])) {
        //$_POST['submit_'.$index] is your submitted button
    }
}

相关问题