我已经创建了简单的表格和表格插入代码。我收到“此页面无法正常运行,本地主机将您重定向了太多次了。尝试清除您的Cookie。”错误。我不确定该如何解决?插入后,用户将被重定向回同一页面(希望为空表格)。新开发者在这里-预先感谢您的帮助!
<?php
$errors = [];
$f['firstname'] = trim($_POST['firstname'] ?? '');
$f['lastname'] = trim($_POST['lastname'] ?? '');
if(isset($_POST['submit'])) {
echo 'doing the validation' . '<br>';
//Validate form entries
if (!$f['firstname']) {
$errors[] = 'First name is required.';
}
if (!$f['lastname']) {
$errors[] = 'Last name is required.';
}
}
if (!$errors) {
// Insert request
echo 'Doing insert' . '<br>';
$qInsert = "INSERT INTO test
(ID, FirstName, LastName)
VALUES (NULL, :firstname, :lastname);";
try {
$stmtInsert = $db->prepare($qInsert);
$stmtInsert->bindParam(':firstname',$f['firstname']);
$stmtInsert->bindParam(':lastname',$f['lastname']);
$stmtInsert->execute();
echo 'after the insert' . '<br>';
header("Location: testform.php");
} catch (PDOException $e) {
logError($e);
echo 'there were errors on insert' . '<br>';
$errors[] = 'Sorry we had a problem and could not submit your request. Please try again.';
}
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<main id="test-request">
<h1>Test Request</h1>
<?php
if ($errors) {
//Show form errors
echo '<h3>Please correct the following errors:</h3>
<ol class="error">';
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo '</ol>';
}
?>
<div class='addform'>
<form action='testform.php' method='post' novalidate>
<label><span>
First Name: </span><input type='text' id='firstname'name='firstname' size='20'
placeholder="Enter First Name" value ="<?= $f['firstname'] ?>" required>
</label>
<label><span>
Last Name: </span><input type='text' id='lastname' name='lastname' size='25'
placeholder="Enter Last Name" value ="<?= $f['lastname'] ?>" required>
</label>
<button name="submit">Add Request</button>
</form>
</div>
</main>
</body>