【问题标题】:HOW to add increment value to $_POST['variable'] in php?如何在 php 中为 $_POST['variable'] 添加增量值?
【发布时间】:2015-08-20 18:46:10
【问题描述】:

我正在使用动态表单,其中用户为他想要的某个字段添加更多输入文本框,并且每个框的名称随着增量变化,例如:

<form method="post" action="somescript.php">
<input type="text" name="textbox" />
<input type="text" name="textbox1" />
<input type="text" name="textbox2" />
<input type="text" name="textbox3" />
.... and so on
</form>

我想在循环之后回显这些数据:

<?PHP
  $k=$_POST['counter']; //counter value coming as post variable
  for($i=1$i<=$k;$k++){
    echo $_POST['textbox'.$i]; //something like this......?
  }
?>

请回复。

【问题讨论】:

  • 这似乎是你想要使用 javascript 的东西,否则每次用户添加新字段时,页面都会重新加载并清除所有现有数据 - 除非你明确通过 GET/POST 参数保存它。

标签: php for-loop forms http-post


【解决方案1】:

改用数组表示法。

<form method="post" action="somescript.php">
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox][" />
.... and so on
</form>

提交表单后,$_POST['textbox'] 将成为一个数组,您可以对其进行循环:

foreach ($_POST['textbox'] as $textbox) {
    echo $textbox;
}

【讨论】:

  • 这应该被认为是正确的答案。
【解决方案2】:

我刚刚遇到这个问题,因为我有需要动态创建的数据块,并且

echo $_POST["textbox$i"];

在没有串联的情况下工作。让我知道这是否是不好的做法,但它适用于我的情况。数组方式对我不起作用。很抱歉将这个发布在一个 3 岁的问题上。我不确定这是否是不好的做法。谢谢。

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2014-04-21
    相关资源
    最近更新 更多