【问题标题】:Form will not submit unless particular non-required field is filled (PHP)除非填写特定的非必填字段(PHP),否则表单不会提交
【发布时间】:2010-11-09 15:53:22
【问题描述】:

我目前有一个表单,要求提供用户的电子邮件、手机号码和手机运营商。没有一个字段被标记为必填项,因为我只需要电子邮件或手机号码。如果用户同时输入电子邮件和电话号码,或者只输入电话号码而没有电子邮件,则表单提交得非常好。但是,如果用户尝试仅使用电子邮件而不使用电话号码提交表单,则表单将不会提交。换句话说,需要一个电话号码才能使表单生效。

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

我在验证电话号码时也遇到了问题(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');
  }

?>

【问题讨论】:

    标签: php forms webforms


    【解决方案1】:
    $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 语句要求正确填写两个字段,如果是,则插入数据。只需遵循您的条件结构即可。

    【讨论】:

    • 混蛋!你打败了我这么多......不过你的答案是正确的,所以我不会发布我自己的。
    • 非常感谢!绝对只是我的马虎。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多