首页 > 解决方案 > 已编辑: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>

标签: phphttpredirect

解决方案


推荐阅读