php - 已编辑:PHP 代码无法识别表单提交
问题描述
我创建了简单的表单和表格插入代码。我收到“此页面无法正常工作 localhost 已将您重定向太多次。尝试清除您的 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>
解决方案
推荐阅读
- python-3.x - 如何在 CSV 文件的列中获取一些值并将其导出到 python 数组
- spring-boot - Spring Integration ServiceActivator 是否适用于项目反应器类型?
- python - 使用 python 脚本从文本文件创建文件夹目录
- mongodb - 使用 Mongo 模板进行排序在 java 中不起作用
- javascript - 将数组转换为对象,其中数组值为对象键且对象值为空
- python - 我正在使用 python 抓取网站上的所有“a”标签。在“a”标签中,我想选择一些单词并存储它们
- php - 在 laravel 中旋转并保存照片
- bash - ssh user@pc 'source ~/.bashrc;printenv' 不来源 bashrc?
- html - 根据特定类的兄弟姐妹调整 div 的大小
- angular - 使用 cellrender 应用的 aggFunc 和 aggFunc 未显示在父行中