首页 > 解决方案 > 提交表单后值未保存

问题描述

我创建了一个包含两列的 mysql 表。一个是ID,另一个是标题。我有一个运行UPDATE代码的文本区域,每当有人提交表单时,它都会在标题下的数据库列中更新。这很好用,但我想在我的文本区域中显示最后输入的提交。我的代码显示了最后输入的值,但是当我重置页面时,它全部变为空白并且不再显示。我在数据库中查看,标题仍然存在,所以我不知道为什么它会从前端消失。

我的页面:

<?php 

$title = 'Admin Panel - Edit';
include '../config.php';

$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);

$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);

?>

<form action="edit.php">
    <?php echo $currentText[0]; ?>
    <input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
    <input type="submit" value="Submit" name="submit" />
</form>

因此,例如,如果我输入 Aleksa,提交后会得到类似edit.php?heading=Aleksa&submit=Submit. 然后当我删除 url 时edit.php,该值丢失。

您可以在这里测试页面:https ://www.easybewussterschaffen.com/admin/edit.php

标签: phpmysql

解决方案


正在发生这种情况,因为它总是在您刷新页面时尝试插入标题。您应该检查请求是GET还是请求POST,并且只有在他们提交表单时才插入它。

更新您的表单方法,将其指定为POST,并专门检查该方法或检查是否存在,$_POST['submit']如下所示:

<?php 

$title = 'Admin Panel - Edit';
include '../config.php';

// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative

    $heading = mysqli_real_escape_string($link, $_REQUEST['heading']);

    $sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
    if(mysqli_query($link, $sql) == false){
         echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);

?>

<form action="edit.php" method="POST">
    <?php echo $currentText[0]; ?>
    <input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
    <input type="submit" value="Submit" name="submit" />
</form>

或者,如果您仍希望发出 GET 请求,则应检查以确保已设置标题:

<?php 

$title = 'Admin Panel - Edit';
include '../config.php';

if (isset($_GET['submit'])) {

    $heading = mysqli_real_escape_string($link, $_GET['heading']);

    $sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
    if(mysqli_query($link, $sql) == false){
         echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);

?>

<form action="edit.php" method="GET">
    <?php echo $currentText[0]; ?>
    <input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
    <input type="submit" value="Submit" name="submit" />
</form>

推荐阅读