如何使用此代码回显多行输入?

时间:2019-03-14 13:08:48

标签: php html arrays post

我希望用户输入动物,然后转到其先前输入下方的行。

    <!DOCTYPE html>
<html>
<head>
    <title> Will Proj. 2</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1> Animal Form</h1>

<form action="" method="post">
  Enter animal:<br>
  <input type="text" name="animal"><br><br>
  <input type="Submit" value="Add Animal">
</form>

<?php
function display()  {
    $animal = $_POST['animal'];
    echo "$animal <br>";
}
if(isset($_POST['animal'])){
    display();
}
    ?>

</body>
</html>

当前每次仅显示1行,并用新输入刷新该行。

2 个答案:

答案 0 :(得分:1)

<?php

session_start();

if (!isset($_SESSION['animals']) && $_POST['animal']) {
   $_SESSION['animals'] = $_POST['animal'].'<br>';
} elseif (isset($_SESSION['animals']) && $_POST['animal']) {
   $_SESSION['animals'] .= $_POST['animal'].'<br>';
}

?>

<!DOCTYPE html>
<html>
<head>
  <title> Will Proj. 2</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
   <h1> Animal Form</h1>
   <form action="" method="post">
     Enter animal:<br>
     <input type="text" name="animal"><br><br>
     <input type="Submit" value="Add Animal">
   </form>

   <?php if (!empty($_SESSION['animals']) { echo $_SESSION['animals']; } ?>
</body>
</html>

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<head>
        <title> Will Proj. 2</title>
        <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
        <h1> Animal Form</h1>

<form action="" method="post">
    Enter animal:<br>
    <?php if(isset($_POST['animal'])){
        foreach($_POST['animal'] as $animal){
            echo '<input type="hidden" name="animal[]" value="'.$animal.'" >';
        }

    } ?>
    <input type="text" name="animal[]"><br><br>
    <input type="Submit" value="Add Animal">
</form>

<?php
function display()  {
        $animals = $_POST['animal'];
        foreach($animals as $animal){
            echo "$animal <br>";
        }
}
if(isset($_POST['animal'])){
        display();
}
?>

</body>
</html>