首页 文章

在用户提交值后,在html中嵌入php以将文本保留在文本框中

提问于
浏览
3
<html>
<body>

<form action="http://localhost/index1.php" method="post">
    Type your name: <input type="text" name="name" value="<?php echo $_POST['name'];?>">
                    <input type="submit" value="Submit">
</form>

</body>
</html>

我想要做的是在用户输入一个值并按下提交按钮后保持在文本框中输入的数据 .

当我按下提交按钮时,它在文本框中发出通知,说明名称是一个未定义的索引,我理解为什么 . $ _POST ['name']没有值 .

我只是想知道是否有办法做到这一点 . 我是php和HTML的初学者 .

5 回答

  • 6
    <?php
    //check whether the variable $_POST['name'] exists
    //this condition will be false for the loading
    if(isset($_POST['name']){
      $name = $_POST['name'];
    }
    else{
      //if the $_POST['name'] is not set
      $name = '';
    }
    
    
    ?>
    
    <html>
    <body>
    
    <form action="http://localhost/index1.php" method="post">
        Type your name: <input type="text" name="name" value="<?php echo $name;?>">
                        <input type="submit" value="Submit">
    </form>
    
    </body>
    </html>
    
  • 1

    试试这个(假设这是 index1.php ,你正在使用 UTF-8 作为你的内容类型)

    <?php
    $name = isset($_POST['name']) ? $_POST['name'] : null;
    ?>
    
    <!-- your HTML, form, etc -->
    
    <input type="text" name="name"
        value="<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>">
    
  • 0

    从@Phil 's answer considering that'使用"isset"不是解决方案( EDIT :我在这一点上看错了看评论),正确的功能是测试$ _POST作为你试图访问的"name"条目:

    <?php
    $name = null;
    if (array_key_exists('name', $_POST)) {
        $name = $_POST['name'];
    }
    //more condensed : $name = array_key_exists('name', $_POST) ? $_POST['name'] : null;
    ?>
    
    <!-- your HTML, form, etc -->
    
    <input type="text" name="name"
        value="<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>">
    

    出现的消息是PHP警告,阅读your environment error_reporting in PHP可能是个好主意 .

  • 3

    @Dallas

    你走在正确的轨道上;这是一个(非常粗糙和脏)的示例表单,它在原始文本框中显示提交的POST字段的值

    <form action="thispage.php" method="post">
        <input type="text" name="mytext" value="<?php echo isset($_POST['mytext'])?$_POST['mytext']:''?>" />
        <input type="submit" value="submit"/>
    </form>
    

    这样做是检查POST字段 mytext 是否已定义,并且(如果是)将该值放回文本框中 . 如果未定义,则仅提供空白值 .

    如果不是't working for you, I' d doublecheck,则文本框的 name 属性与您在$ _POST中搜索的键值相匹配 .

  • 0

    由于你的表单操作属性指向index1.php,我假设给定的HTML代码是在相同的index1.php中给出的,在这种情况下,你必须这样做

    <html>
    <body>
    
    <form action="http://localhost/index1.php" method="post">
        Type your name: input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];}?>
                        input type="submit" value="Submit">
    </form>
    
    </body>
    </html>
    

    <?php echo isset($_POST['name'])?$_POST['name']:''?> 是使value属性成为条件的另一种方法

相关问题