I have created simple form and table insert code. I am getting the 'This page isn’t working localhost redirected you too many times. Try clearing your cookies.' error. I am not sure how to fix this? After the insert the user is redirected back to same page (with hopefully empty form). New developer here - thanks in advance for any help!
<?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>
';` on the screen, because the browser will ignore the response content returned by your script and instead proceed immediately to doing the instructed redirect. Another non-browser client (such as PostMan, for instance) which doesn't automatically follow redirect headers would enable you to see it, though. – ADyson Dec 03 '19 at 20:36