无法弄清楚如何在 PHP 中格式化此逻辑语句

Can't figure out how to format this logic statement in PHP

我有一些 PHP 用于验证表单,一旦验证完成,表单中的数据就会发送到数据库中。我的问题实际上不是代码问题,只是我不知道如何编写 if-else 语句块。

基本上我有所有这些 if 语句来检查表单字段之一是否为空或不符合标准,然后是一个相应的 else 语句,它只保存他们输入的数据,所以当表单重新加载他们不必再次输入。目前,我在末尾有一个 else 语句,当所有字段都经过验证时,它会将所有数据发布到我的数据库中——问题是我有太多的 else 语句,这给了我错误。

所以我认为我必须将整个代码块包装在一个 if-else 语句中,基本上就是说如果没有错误,执行将数据发送到数据库的 else。

基本上我已经完成了 else,我只需要帮助想想为 if

设置什么条件

这是我的代码

//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());

## Initialise varialbes to null ##
$nameError ="";
$emailError ="";
$categoryError ="";
$messageError ="";

$validName ="";
$validEmail ="";
$validMessage ="";


## On submitting form below function will execute ##
if(isset($_POST['submit']))
{
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$category = $_POST['category'];

//if name is less than 10 characters
if (empty($_POST["name"]) || strlen($name)<10) 
{
    $nameError ="* Name is too short";
}

else
{
    $validName = $_POST["name"];
}   


//if email is too short or is not the right format
if (empty($_POST["email"]) || !preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email) || strlen($email)<10 ) 
{
    $emailError = "* You did not enter a valid email";
    $validEmail = $_POST["email"];
}
else
{
    $validEmail = $_POST["email"];
}   

//if a category is not chosen
if (empty($_POST["category"])) {
    $categoryError = "* Please select a category";
} 

//if the message is left blank
if (empty($_POST["message"]) || strlen($message)<25 ) {
    $messageError = "* Your message is too short";
} 
else {
    $validMessage = $_POST["message"];

}

//If there are no errors, email details to admin
else {
        // variables to send email
        $to = "e.reilly4@nuigalway.ie";
        $subject = "Contact Form";
        $body = "\r\n
        Category: $_POST[category] \r\n
        Message: $_POST[message] \r\n
        Name: $_POST[name] \r\n
        Email: $_POST[email]";          

        //  Email Function
        mail($to,$subject,$body);    

        //Insert the data into the database
        $conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);

        $conn->close(); 

        echo "sent to database";
    }
}

?> <!-- End of PHP -->

基本上我需要想出另一个 if 语句放在第一个语句之后,但对于我来说,我想不出一个条件。我想如果我做了一个布尔值是假的,一旦所有数据都正确,它就会变成真,但我不知道如何实现它。只是在寻找关于如何去做的任何想法

当我进行验证时,我个人会尝试想出一个函数来类似地验证每个值。您应该边做边做一些检查。这是对您所拥有的一些符号的重组:

<?php
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());

// I usually build a simple validate function
// This is just an example, you can edit based on your needs
function validate_var($value = false,$type = 'str')
    {
        // Validate the different options
        if(!empty($value) && $value != false) {
            switch ($type) {
                    case ('str'):
                        return (is_string($value))? true:false;
                    case ('num') :
                        return (is_numeric($value))? true:false;
                    case ('email'):
                        return (filter_var($value,FILTER_VALIDATE_EMAIL))? true:false;

                }

            // This will just check not empty and string length if numeric
            if((is_numeric($type) && !empty($value)) && (strlen($value) >= $type))
                return true;
            }

        // Return false if all else fails
        return false;
    }

// On post, proceed
if(isset($_POST['submit'])) {
        //assign details to be posted to variables
        $name       =   $_POST['name'];
        $email      =   $_POST['email'];
        // Strip the message of html as a precaution
        // Since you are not binding in your sql lower down, you should probably use
        // htmlspecialchars($_POST['message'],ENT_QUOTES))
        // or use the binding from the mysqli_ library to escape the input
        $message    =   htmlspecialchars(strip_tags($_POST['message']),ENT_QUOTES));
        // Do a "just-incase" filter (based on what this is supposed to be)
        $category   =   preg_replace('/[^a-zA-Z0-9]/',"",$_POST['category']);

        // Validate string length of 10
        if(!validate_var($name,10))
            $error['name']      =   true;
        // Validate email
        if(!validate_var($email,'email'))
            $error['email']     =   true;
        // Validate message length
        if(!validate_var($message,25))
            $error['message']   =   true;
        // Validate your category
        if(!validate_var($category))
            $error['category']  =   true;

        // Check if there are errors set
        if(!isset($error)) {
                // Use the filtered variables,
                // not the raw $_POST variables
                $to         =   "e.reilly4@nuigalway.ie";
                $subject    =   "Contact Form";
                $body       =   "\r\n
                Category: $category \r\n
                Message: $message \r\n
                Name: $name \r\n
                Email: $email";          

                // Don't just send and insert, make sure you insert into your databases
                // on successful send
                if(mail($to,$subject,$body)) {
                        //Insert the data into the database
                        $conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
                        $conn->close();
                        echo "sent to database";
                    }
                else
                    echo 'An error occurred.';
            }
        else {
                // Loop through errors cast
                foreach($error as $kind => $true) {
                        switch ($kind) {
                                case ('name') :
                                    echo "* Name is too short";
                                    break;
                                case ('email') :
                                    echo "* You did not enter a valid email";
                                    break;
                                case ('category') :
                                    echo "* Please select a category";
                                    break;
                                case ('message') :
                                    echo "* Your message is too short";
                                    break;
                            }
                    }
            }
    }
?>