使用此IF语句的最佳方式和&&逻辑表达

时间:2012-01-18 12:15:35

标签: php mysql if-statement guid

require_once('mysqli_connect.php');

$errors = array(); 


if(empty($_POST['senFirstName']) && empty($_POST['senLastName']) 
&& empty($_POST['recFirstName']) && empty($_POST['recLastName']) 
&& empty($_POST['proName']) && empty($_POST['proWeight']) 
&& empty($_POST['traNo']) &&  empty($_POST['shipDate']) 
&& empty($_POST['deliDate'])) {

    $errors[] = 'Please make sure you type in all the information.';

}
else {
    $sfn = mysqli_real_escape_string($dbc, trim($_POST['senFirstName']));
    $sln = mysqli_real_escape_string($dbc, trim($_POST['senLastName']));
    $rfn = mysqli_real_escape_string($dbc, trim($_POST['recFirstName']));
    $rln = mysqli_real_escape_string($dbc, trim($_POST['recLastName']));
    $pn = mysqli_real_escape_string($dbc, trim($_POST['proName']));
    $pw = mysqli_real_escape_string($dbc, trim($_POST['proWeight']));
    $traNo = mysqli_real_escape_string($dbc, trim($_POST['traNo']));
    $shipDate = mysqli_real_escape_string($dbc, trim($_POST['shipDate']));
    $deliDate = mysqli_real_escape_string($dbc, trim($_POST['deliDate']));
    $status = mysqli_real_escape_string($dbc, trim($_POST['status']));
    $shiptype = mysqli_real_escape_string($dbc, trim($_POST['shiptype']));
    }   


if(empty($errors)) { // If everything's OK.

$query = "SELECT traNo, CONCAT(recFirstName, ' ', recLastName) AS recieverName, proName, CONCAT(senFirstName, ' ', senLastName) AS senderName, status, shiptype FROM tracking, rel_tracking_reciever, reciever, product, sender
    WHERE traNo='$traNo' AND tracking.traId = rel_tracking_reciever.traId AND reciever.recId = rel_tracking_reciever.recId AND tracking.proId = product.proId AND tracking.senId = sender.senId";

    $result = @mysqli_query($dbc, $query); 
    $num = mysqli_num_rows($result);

    if ($num) { // tracking number was found

    while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) {


        echo '<div id="error">';
        echo "<p>This tracking number <b>{$row['traNo']}</b> has already been assigned to <b>{$row['senderName']}</b></p>\n";
        echo '</div>';
    }
    mysqli_free_result ($result); // Free up the resources.
    } 

1)我想使用&amp;&amp;和多个IF条件来验证输入框。逻辑表达式,但它将空表单提交到数据库中。 注意:我故意省略了货件和状态输入框,因为默认情况下选项不能为空。

2)有没有办法可以自动生成跟踪号码而无需手动输入。我试过GUID但是没有得到它。

谢谢..

2 个答案:

答案 0 :(得分:2)

您必须设置要验证的ID - 没有抱怨。

你可以这样做:

$ids = array('senFirstName', 'senLastName', 'recFirstName', 'recLastName' /* ... and more */);
$valid = true;

foreach ( $ids as $id ) {
  if ( empty($_POST[$id]) ) {
    $valid = false;
  }
}

if ( $valid === true ) {
  // everything's ok
} else {
  $errors[] = 'Please make sure you type in all the information.';
}

答案 1 :(得分:1)

你需要||,而不是&amp;&amp;如果你想测试,如果你是空的。

否则你会证明,如果所有这些都是空的。

(抱歉英语不好)

if(empty($_POST['senFirstName']) || empty($_POST['senLastName'])  ...