无法验证并在表单上插入日期

时间:2014-03-18 01:52:18

标签: php forms validation insert

我试图创建一个验证输入字段的表单,然后将数据发送到mysql数据库。我可以让输入验证工作,或者插入到数据库中的数据,但不是两者都是..继承我的代码:

<?php require_once('../php/pdo_connect.php'); 
// define variables and set to empty values
$first_name_err = $last_name_err = $cell_err = $email_err = FALSE;
$first_name = $last_name = $cell = $email = FALSE;

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
   if (empty($_POST["first_name"]))
     {$first_name_err = "First name is required";}
   else
     {
     $first_name = test_input($_POST["first_name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
       {
       $first_name_err = "Please don't use hypens or other special characters";
       }
     }

   if (empty($_POST["last_name"]))
     {$last_name_err = "Last name is required";}
   else
     {
     $last_name = test_input($_POST["last_name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
       {
       $last_name_err = "Please don't use hypens or other special characters";
       }
     }

  if (empty($_POST["cell"]))
    {$cell_err = "Phone number is required";}
  else
    {
    $cell = test_input($_POST["cell"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[\+0-9\-\(\)\s]*$/",$cell))
      {
      $cell_err = "Invalid cell phone number";
      }
    }

   if (empty($_POST["email"]))
     {$email_err = "Email address is required";}
   else
     {
     $email = test_input($_POST["email"]);
     // check if e-mail address syntax is valid
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
       {
       $email_err = "Invalid email format";
       }
     }
if ($first_name_err = false){
        //insert info into db
        $query = $pdo->prepare("INSERT INTO `guestlist_page_requests` (first_name, last_name, cell, email) VALUES (?, ?, ? ,?)");
        $query->bindValue(1, $first_name);
        $query->bindValue(2, $last_name);
        $query->bindValue(3, $cell);
        $query->bindValue(4, $email);
        $query->execute();
        header('Location: ../index.php');
    }else{
        //not enough data to submit to db
    }

    }

我尝试了这一行的一些不同变体:

if ($first_name_err = false){

但是我不确定我应该把它放在这里?

这条线几乎让它起作用:

if (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['cell']) && !empty($_POST['email'])){

但随后它会提交带有错误的数据,除非其中一个字段为空。

这似乎也不正常:

if ($first_name_err = false){

0 个答案:

没有答案