找出用户填写的内容

时间:2011-06-21 18:13:56

标签: php

我正在试图找出如何找到我需要执行的步骤,如果它是用户名或者是用户提交的电子邮件地址。

// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }


// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) { 

    $errors = "yes";
    $message = "You must enter a value for either the username or email address!";

    $output = array('errorsExist' => true, 'message' => $message);

} else if (!empty($username) && !empty($email)) {

    $errors = "yes";
    $message = "You can only enter a value for the username or email address!";

    $output = array('errorsExist' => true, 'message' => $message);        

} else {

}

3 个答案:

答案 0 :(得分:2)

else if ( empty( $username ) ) {
    // Output username error
}
else if ( empty( $email ) ) {
    // Output email error
}

但是,在这种情况下,我会跳过if / else语句,只使用错误条件:

$is_error = false;
if ( empty( $username ) ) {
    $is_error = true;
    $error_messages[] = 'Your username error message';
}
if ( empty( $email ) ) {
    $is_error = true;
    $error_messages[] = 'Your email error message';
}

if ( $is_error ) {
    // Output all error messages
}
else {
    // Perform success event
}

答案 1 :(得分:2)

// Assign variable values if there is values
if ((isset($_POST['username'])) && ($_POST['username'] !== NULL) && (!empty($_POST['username']))) { $username = trim($_POST['username']); }
if ((isset($_POST['email'])) && ($_POST['email'] !== NULL) && (!empty($_POST['email']))) { $email = trim($_POST['email']); }


// IF BOTH FIELDS ARE EMPTY, ERROR CONDITION EXISTS
if (empty($username) && empty($email)) { 

    $errors = "yes";
    $message = "You must enter a value for either the username or email address!";

    $output = array('errorsExist' => true, 'message' => $message);

} else if (!empty($username) && !empty($email)) {

    $errors = "yes";
    $message = "You can only enter a value for the username or email address!";

    $output = array('errorsExist' => true, 'message' => $message);        

} else {
   if(!empty($username)) {
        //Do some things if the user entered only the username
   }
   else {
        //Do some things if the user entered only email
   }
}

答案 2 :(得分:2)

我认为您需要在最后else中执行您的步骤,只有当用户名和电子邮件都不为空或输入时才会执行。所以在最后的其他方面,你可以做类似

的事情
if (!empty($username)) {
} else {
}

另一方面,我认为在填充$ username或$ email时你不需要进行所有3次检查;第一个和最后一个应该足够了,例如:

if (isset($_POST['username']) && !empty($_POST['username']) {
    $username = $_POST['username'];
}