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

时间:2015-04-15 19:55:33

标签: php validation if-statement logic

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

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

所以我想我必须将整个代码块包装在一个if-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语句,但对于我的生活,我想不出有条件。我想如果我做了一个假的布尔值,并且一旦所有数据都正确就会变为真,但我无法弄清楚如何实现它。只是寻找关于如何去做的任何想法

1 个答案:

答案 0 :(得分:0)

当我进行验证时,我个人尝试提出一个能够同样验证每个值的函数。你去的时候应该做一些检查。以下是对某些符号的重构:

<?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;
                            }
                    }
            }
    }
?>