我有一个表单 book-form.php,它向 book-list.php 发送输入并显示图书列表页面,如果没有错误(错误意味着书名太短或太长)。如果发生错误,我会在表单页面上收到一条错误消息,并停留在那里而不重定向到图书列表页面。
已编辑:我的问题是,当它重定向到 book-list.php 时,没有输出(在 book-form.php 中输入的值)。我错过了什么?
我的表格代码:
<?php
$file = fopen('book.txt', 'a');
$title = $_POST['title'] ?? '';
fwrite($file, $title . PHP_EOL);
fclose($file);
if (isset($_POST['title'])) {
if (strlen($_POST['title']) > 2 and strlen($_POST['title']) < 24) {
header("Location: book-list.php");
exit();
}
else {
print "Book title should contain 3 to 23 characters";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Library</title>
</head>
<body id="book-form-page">
<table>
*meaningless html*
<td>
<a href=book-list.php id="book-list-link">Books</a> |
<a href=book-form.php id="book-form-link">Add books</a>
</td>
*meaningless html*
<td>
<table>
<form method="post" action="book-form.php">
<tr>
<td align="right">Title:</td>
<td><input size="40%" type="text" name="title" value="<?php echo $title; ?>"></td>
</tr>
<tr>
<td></td>
<td align="right"><button type="submit" name="submitButton">Save</button></td>
</tr>
</form>
*doesn't matter further*
这应该解释一个可能的工作流程。 它仅用于教育目的,不适用于真正的 Web 应用程序:外面的 WWW 是一片丛林 ;-)
<?php
// presets
$error = '';
$title = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// if we are here it's because we arrived from form-submitting
$title = $_POST['title'];
$l = strlen($title);
if ($l < 3 || $l > 23) {
$error = 'Book title must contain 3-23 chars!'; // we'll display this in the page
}
else {
// ----- it's all right, save data here
// after saving data we can redirect to the list
header ('Location: book-list.php'); // it's time for a change of scenery
die; // after 'header' this is a best practice
}
}
?>
<!-- if we are here it's because we arrived from start (GET) or from a form-submission (POST) with errors -->
<html lang="en">
<head>
<!-- all the needed stuff for header here -->
</head>
<body> <!-- add all properties that you need to body -->
<!-- all the needed stuff for body/page here -->
<table>
<tr>
<td><?= $error ?></td>
</tr>
<tr>
<td>
<form method="post"> <!-- no action = we come back to this php after submitting the form -->
<table>
<tr>
<td align="right">Title:</td>
<td><input size="40%" type="text" name="title" value="<?= $title ?>"></td>
</tr>
<tr>
<td align="right"><button type="submit" name="submitButton">Save</button></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body
</html>