我目前正在研究一个代码,可以在任何事情发生之前进行基本输入。这样它就可以将一些东西插入数据库,以便我可以提取该 ID 并插入该 ID 上。这将创建自动保存类型的插入。
我的页面中有一些呈现调用,以确保正确提交信息,并发现自己在呈现和输入方面遇到问题,因为呈现将导致插入被调用两次,而不是重定向页面。知道我如何让这个插入调用一次,并使代码按预期运行吗?
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// insert null into database to create the save point
if ($stmt = $mysqli->prepare("INSERT INTO test_table (name, email, notes) VALUES ('x', 'x', 'x')"))
{
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Auto-Save SQL statement.";
}
// gets id of null insert to update upon.
$as_id = $mysqli->insert_id;
printf ($as_id);
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$name = htmlentities($_POST['name'], ENT_QUOTES);
$email = htmlentities($_POST['email'], ENT_QUOTES);
$notes = htmlentities($_POST['notes'], ENT_QUOTES);
// check that name, email are not empty.
if ($name == '' || $email == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($name, $email, $notes, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("UPDATE test_table SET name=?, email=?, notes=? WHERE id=?"))
{
$stmt->bind_param("ssss", $name, $email, $notes, $as_id);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirect the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
请参阅 header() 的 PHP 手册页,这里: http://php.net/manual/en/function.header.php
请记住,在任何实际输出之前必须调用 header() 通过普通 HTML 标记、文件中的空行或从 PHP 发送。
此外,实际上,只有在所有验证都通过后,您的插入才应该发生。在你的脚本中,实际上没有理由在此之前发生它,除非你最终打算将$as_id传递到renderForm() - 例如,允许外围表单在填充核心记录之前保存关系数据,但这是一个糟糕的模式。
就您的代码而言,您的插入发生在表单呈现之前,并在表单提交之后再次发生。每次用户验证失败并重新提交表单时,都会再次执行。
也就是说,您可以通过交换以下内容来获得所需的结果:
printf ($as_id);
像这样:
header('Location: view.php?id='.$as_id);
但是,请注意,这样做,您永远不会遇到if(isset($_POST['submit']))
- 我假设您将此代码块复制到"新记录"条件之外,可能是在"编辑记录"条件或类似条件下。
理想情况下,您希望完全放弃这种方法,转而使用具有 RESTful 路由的 MVC 风格架构......