【问题标题】:Printing together multiple submits from the same text box从同一个文本框中打印多个提交
【发布时间】:2015-01-24 04:28:26
【问题描述】:

我有一个简单的任务,我很生气没有让它工作。 我有一个文本框和一个提交按钮,我的目标是打印在一行中提交的所有内容。

水果:_________ SUBMIT_BUTTON(购买)

列表:..

所以当我提交一个苹果时,我得到了

List: apple

然后是香蕉

List: apple banana

你明白了。

我的想法是将新提交的字符串添加到变量中并打印出来。

<html>
<head></head>
<body>
  <form method="post" action="">
    Fruit:
    <input type="text" name="text" />
    <input type="submit" name="button" value="Buy" />
  </form>

<?php
$fruit = '';
if(isset($_POST['button'])) {
  $fruit = $fruit . ' ' . $_POST['text'];
  echo 'List: ', $fruit;
}
?>
</body>
<html>

但我只得到最后提交的单词。似乎每次我点击“购买”$fruit = '';执行。

【问题讨论】:

  • 我注意到的问题是,您在每次加载页面时不断将fruit 变量重置为空白... $fruit='';

标签: php html forms input output


【解决方案1】:

或者,如果您希望值保持不变,您可以利用会话并创建一个容器来保存提交的值。粗略的例子:

<?php

session_start();
// initializations
if(!isset($_SESSION['fruits'])) {
    $_SESSION['fruits'] = array();
}


if(isset($_POST['button'])) {
    $_SESSION['fruits'][] = $_POST['text']; // push the submitted value inside
    echo implode(' ', $_SESSION['fruits']); // join all the values inside it and print it
}
?>

<body>
    <form method="post" action="">
        Fruit:
        <input type="text" name="text" />
        <input type="submit" name="button" value="Buy" />
    </form>
</body>

【讨论】:

  • 会话做到了。非常感谢。
  • @Nikola 我很高兴这有帮助
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多