我希望此表单将数据库中"标题"和"摘要"列中找到的任何数据加载到输入字段中,以便于编辑。然后,在用户提交表单后,内容将转储回数据库,新的"值"将显示在表单中。我的问题是"转储"部分工作正常,但是当我刷新页面或导航回表单时,不显示任何数据,表中的数据已被空格替换......我该如何解决这个问题?
表单 PHP
<!-- Process POST Data and dump into DB -->
<?php
$header1 = $_POST['header1'];
$summary1 = $_POST['summary1'];
$handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE myTable SET header='$header1', summary='$summary1' WHERE id=1";
try {
$stmt = $handler->prepare($sql);
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
$handler = null;
?>
<!-- Get mysql data -->
<?php
$handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fetchData = $handler->prepare("SELECT * FROM newsletters WHERE id=1");
$fetchData->execute();
$data = $fetchData->fetchAll();
?>
<!-- form -->
表单 HTML
<form action="index.php" method="POST">
<input type="text" name="header1" value="<?php foreach ($data as $Data){echo $Data['header'];} ?>">
<textarea name="summary1" rows="5" value="<?php foreach ($data as $Data){echo $Data['summary'];} ?>"></textarea>
<input type="submit" name="submit1" value="Submit">
</form>
假设您使用相同的脚本来显示表单并处理提交,则需要在更新数据库之前检查表单是否已提交。
if (isset($_POST['header1'], $_POST['summary1'])) {
$header1 = $_POST['header1'];
$summary1 = $_POST['summary1'];
$handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE myTable SET header= :header , summary= :summary WHERE id=1";
try {
$stmt = $handler->prepare($sql);
$stmt->execute(array(':header' => $header1, ':summary' => $summary1));
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
$handler = null;
}
我还演示了如何在预准备语句中使用参数来防止 SQL 注入。