我希望此表单加载"标题中的任何数据"和"摘要"我的数据库中的列进入输入字段以便于编辑。然后,在用户提交表单后,内容将被转储回DB和新的"值"显示在表格中。我的问题是"倾销"部分工作正常,但是当我刷新页面或导航回到表单时,没有数据显示,表中的数据已被空格替换......我该如何解决这个问题?
//表单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>
答案 0 :(得分:0)
假设您使用相同的脚本显示表单并处理提交,您需要在更新数据库之前检查表单是否已提交。
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注入。