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


Embed php in html to keep text in text box after user submits a value

<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 的初学者。

<?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>

试试这个(假设这是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') ?>">

从@Phil的回答来看,考虑到使用"isset"不是解决方案(编辑:我在这一点上错了,请参阅评论(,正确的功能是测试$_POST作为您尝试访问的"名称"条目:

<?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 警告,阅读有关您的环境error_reporting PHP 可能是个好主意。

@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 是否已定义,并(如果是(将该值放回文本框中。如果未定义,则仅给出一个空白值。

如果它不适合您,我会仔细检查文本框的 name 属性与您在 $_POST 中搜索的键值匹配。

由于您的表单操作属性指向 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']:''?>是使值属性有条件的另一种方法