!empty()参数格式错误?

时间:2015-05-09 21:32:50

标签: php html forms

我正在建立一个表格。我已设置它,以便在按下提交按钮时,显示包含数据的HTML页面。如果未单击提交,则显示表单。

我的问题是,当我将!empty()参数添加到if((isset($_POST['submit'])时,我的PHP页面没有显示任何内容。我添加了!empty()参数来检查是否单击了提交按钮并且所有表单字段都不为空,并且表单输出为false。我认为!empty()验证的格式不正确。表单运行正常,没有&& (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && !empty($_POST['user_state']) && !empty($_POST['zip_code'])))

我已经仔细检查过,看不到任何错误。任何可能是问题的见解都将受到赞赏。

<?php

if((isset($_POST['submit']) && (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && !empty($_POST['user_state']) && !empty($_POST['zip_code'])))  {
    $first = $_POST['first_name'];
    $last = $_POST['last_name'];
    $street = $_POST['user_street'];
    $city = $_POST['user_city'];
    $state = $_POST['user_state'];
    $zip = $_POST['zip_code'];
    $output_form = false; 

    }

    else {
        $output_form = true;
    }
?>


<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

    <body>

    <?php
    if($output_form) {
    ?>

    <h1>PHP Sticky Form</h1>

    <form action="<?= $_SERVER[ 'PHP_SELF' ]; ?>" method="post" name="userForm">
        <p>First Name: <input type="text" id="first_name" name="first_name" value="<?=$first ?>" /></p>
        <p>Last Name: <input type="text" id="last_name" name="last_name" value="<?=$last ?>" /></p> 
        <p>Street Address: <input type="text" id="user_street" name="user_street" value="<?=$street ?>" /></p> 
        <p>City: <input type="text" id="user_city" name="user_city" value="<?=$city ?>" /></p> 
        <p>State: <input type="text" id="user_state" name="user_state" value="<?=$state ?>" /></p> 
        <p>Zip Code: <input type="text" id="zip_code" name="zip_code" value="<?=$zip ?>" /></p> 
        <p><input type="submit" name="submit" /></p>

    </form>

    <?php
     } else {
    ?>
        <h1>Your Address Information</h1>
        <p>NAME: <?= $first . ' ' . $last ?></p>
        <p>STREET:  <?= $street ?></p>
        <p>CITY, STATE, ZIP: <?= $city . ' ' . $state . ", " . $zip ?></p>

    <?php
     }
    ?>

    </body>

</html>

2 个答案:

答案 0 :(得分:0)

你的主要问题是你正在使用&amp;&amp;用于检查$ _POST中的值,

if(isset($_POST['submit'] && (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && ...

这意味着如果表单(ex. $_POST['first_name'] is empty)中有一个值,那么它就不会显示您的输出数据。

您可以执行以下操作:

if(isset($_POST['submit'])){
  //if $_POST['first_name'] is not empty, get value, else get error
  $first = !empty($_POST['first_name']) ? $_POST['first_name'] : 'empty firstname';
  //check other values as well
  ...
  $output_form = false; 
}else{
  $output_form = true; 
}

答案 1 :(得分:0)

空的($ _ POST ['zip_code'])))之后

你可能错过了一个额外的)。