除非填写特定的非必填字段,否则表格不会提交(PHP)

时间:2010-11-09 15:53:23

标签: php forms webforms

我目前有一个表格,要求用户的电子邮件,手机号码和手机运营商。没有字段被标记为必需,因为我只需要电子邮件或单元格号码。如果用户同时输入电子邮件和电话号码或仅输入电话号码且没有电子邮件,则表单提交完全正常。但是,如果用户尝试仅使用电子邮件而不是电话号码提交表单,则表单将不会提交。换句话说,需要一个电话号码才能使表格正常工作。

我该怎样防止这种情况?我希望用户能够只输入他们的电子邮件或电话;也不应该是强制性的。任何帮助将不胜感激。

我在验证电话号码时遇到问题(FILTER_VALIDATE_INT不适用于10位数字),但这是我稍后会解决的问题。

表格的代码如下:

<form action="insert.php" method="post" id="signup">
  <p>
    <input type="text" id="email" name="email" value="E-mail" /><br/>
    <input type="text" id="phone" name="phone" value="Phone" /><br/>
    <select id="carrier" name="carrier">
      <option value="" selected="selected">Carrier</option>
      <option value="att">AT&amp;T</option>
      <option value="sprint">Sprint</option>
      <option value="tmobile">T-Mobile</option>
      <option value="verizon">Verizon</option>
    </select>
  </p>
  <p>
    <input type="image" src="images/button.gif" alt="Register!" />
  </p>
</form> 

PHP脚本的代码如下:

<?php
$con = mysql_connect("dbhost","dbuser","dbpass");
if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbname", $con);

$filters = array(
  "email"=> FILTER_VALIDATE_EMAIL,
  "phone" => FILTER_VALIDATE_INT,
  );

$result = filter_input_array(INPUT_POST, $filters);

if (!$result["email"])
  {
    echo("E-mail is invalid.<br />");
  }
elseif(!$result["phone"])
  {
    echo("Phone is invalid.<br />");
  }
else
  {
    $sql="INSERT INTO dbtable (email,phone,carrier)
    VALUES
    ('$_POST[email]','$_POST[phone]','$_POST[carrier]')";
    if (!mysql_query($sql,$con))
      {
        die('Error: ' . mysql_error());
      }

    mysql_close($con);
    header('Location: http://pagename.com');
  }

?>

1 个答案:

答案 0 :(得分:3)

$result = filter_input_array(INPUT_POST, $filters);

if(!empty($result["email"]) || !empty($result["phone"])){
  //Being here means that either the email or the phone has passed
  //your validation and therefore you should be able to insert in the db.
}else{
  //Being here means that neither the phone or email have been filled
  //and should show a message like "Please fill at least one field :)"
}

您的问题来自于if语句要求正确填写BOTH字段,如果是,则插入数据。只需遵循您的条件结构。