在创建将数据提交到数据库并发送电子邮件的组合PHP脚本时遇到问题

时间:2019-07-12 22:23:15

标签: php html mysql email

对于PHP来说这是很新的东西,我一直试图将工作代码组合成一个函数,但没有成功。在花了整整一天时间尝试调整它以使其工作时,我决定寻求指导和帮助

我曾尝试重组代码顺序,但没有成功。

<?php

/*                Global Setup                                        */

 // Declare HTML Form, Post Method Variables
$yourname = check_input($_POST['yourname'], "Enter your name");
$subject  = check_input($_POST['subject'], "Write a subject");
$email    = check_input($_POST['email']);
$comments = check_input($_POST['comments'], "Write your comments");


/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}


/*                        Database Setup               */

// Input Validation , Variables Should not be empty
if (!empty($yourname) || !empty($subject) || !empty($comments) || !empty($email) ){

    //Enter DB Credentials
    $host = "localhost"; /*Godday C-Pannel MySQL Server Host Name*/
    $dbname = "ContactDB"; /*Database Name*/
    $dbUsername = "uncontact"; 
    $dbPassword = "pwcontact";


    //create connection
    $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);

     // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    } else {

         /*MySQL Insert Data Statement*/
         $SQL_INSERT = "INSERT INTO contact_tbl (name, email, subject, message) values(?, ?, ?, ?)"; //Insert variables into table

         //Validate Insert 
            if ($conn->query($SQL_INSERT) === TRUE) {
                  //Prepare statement
                  $stmt = $conn->prepare($SQL_INSERT);



                  $stmt->bind_param("ssss", $yourname, $email, $subject, $comments);


                  $stmt->execute();



                  echo "Record inserted sucessfully";

            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }


         $stmt->close(); //Close Statement
         $conn->close(); //Close Database Connection


/*                          Email Setup                        */


            /* Set e-mail recipient */
            $recipientemail  = "recipient@contact.com";

            /* Let's prepare the message for the e-mail */
            $message = "Hello!

            Your a new form request has been submitted by:

            Name: $yourname
            E-mail: $email

            Comments:
            $comments

            End of message
            ";

            /* Send the message using mail() function */
            mail($recipientemail, $subject, $message);

            /* Redirect visitor to the thank you page */
            header('Location: thanks.htm');
            exit();

            /* Functions we used */
            function check_input($data, $problem='')
            {
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                if ($problem && strlen($data) == 0)
                {
                    show_error($problem);
                }
                return $data;
            }

            function show_error($myError)
            {
            ?>
            <b>We apologize for the inconvenience, an error occurred.</b><br />
            <?php echo $myError; ?>
            <?php
            exit();
            }



    }
} else {
    echo "All fields are required";
    die(mysql_error());
}


?>

任何帮助将不胜感激。

下面是应用Barmar建议的更改后的代码,但是仍然无法完成这项工作。 (现在包括功能脚本的重定位)


<?php
    /***********************************************************************************************/
    /*                                         Global Setup                                        */
    /***********************************************************************************************/

    //Function Used to verify user form input fields
    function check_input($data, $problem=''){
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        if ($problem && strlen($data) == 0)
        {
            show_error($problem);
        }
        return $data;
    }

    //Function Used to notify user of incorrect  user input
    function show_error($myError){
        ?>
        <b>We apologize for the inconvenience, an error occurred.</b><br />
        <?php echo $myError; ?>
        <?php
        exit();
    }


     // Declare HTML Form, Post Method Variables
    $yourname = check_input($_POST['yourname'], "Enter your name");
    $subject  = check_input($_POST['subject'], "Write a subject");
    $email    = check_input($_POST['email']);
    $comments = check_input($_POST['comments'], "Write your comments");


    /* If e-mail is not valid show error message */
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
    {
        show_error("E-mail address not valid");
    }

    /***********************************************************************************************/
    /*                                       Database Setup                                        */
    /***********************************************************************************************/


    // Input Validation , Variables Should not be empty
    if (!empty($yourname) && !empty($subject) && !empty($comments) & !empty($email)  ){

        //Enter DB Credentials
        $host = "localhost"; 
        $dbname = "ContactDB";
        $dbUsername = "uncontact"; 
        $dbPassword = "pwcontact";  


        //create connection
        $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);

        //error grabber
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

         // Check connection
        if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        } else {

             /*MySQL Insert Data Statement*/
             $SQL_INSERT = "INSERT INTO contact_tbl (name, email, subject, message) values(?, ?, ?, ?)"; //Insert variables into table

             //Validate Insert 
                if ($stmt = $conn->prepare($SQL_INSERT)) {
                      /*Prepare statement: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

                      The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.   */

                      $stmt->bind_param("ssss", $yourname, $email, $subject, $comments);

                        /*  This function binds the parameters to the SQL query and tells the database what the parameters are. The "ssss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.

                        The argument may be one of four types:

                        i - integer
                        d - double
                        s - string
                        b - BLOB */

                     $stmt->execute(); 

                       /*Execute:Application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values  */

                        if ($stmt->execute()) {
                            echo "Record inserted successfully";
                        } else {
                            echo "Error: " . $stmt->error;
                        }

                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }


             $stmt->close(); //Close Statement
             $conn->close(); //Close Database Connection


    /***********************************************************************************************/
    /*                                          Email Setup                                        */
    /***********************************************************************************************/


                /* Set e-mail recipient */
               $recipientemail  = "recipient@contact.com"; 

                /* Let's prepare the message for the e-mail */
                $message = "Hello!

                Your a new form request has been submitted by:

                Name: $yourname
                E-mail: $email

                Comments:
                $comments

                End of message
                ";

                /* Send the message using mail() function */
                mail($recipientemail, $subject, $message);

                /* Redirect visitor to the thank you page */
                header('Location: thanks.htm');
                exit();



    /***********************************************************************************************/


        }

    } else {
        echo "All fields are required";

    }


?>

1 个答案:

答案 0 :(得分:0)

您的查询中包含参数,您不能将其与$conn->query()一起使用。更改:

if ($conn->query($SQL_INSERT) === TRUE) {
    $stmt = $conn->prepare($SQL_INSERT);
    ...

if ($stmt = $conn->prepare($SQL_INSERT)) {
    ...

即使执行查询遇到错误,您也会回显记录已成功插入。您应该使用:

if ($stmt->execute()) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $stmt->error;
}

您提供的所有输入字段的测试错误。

if (!empty($yourname) || !empty($subject) || !empty($comments) || !empty($email) ){

应该是

if (!empty($yourname) && !empty($subject) && !empty($comments) & !empty($email) ){
如果填写了任意个输入,则

||为真,如果填写了 all ,则&&为真。

另一个问题是,您在check_input()块中有show_error()if的定义。这意味着在执行if并且条件成功之前,将不会定义函数。但是您是在if之前调用它们,因此您应该会遇到有关未定义函数的错误。函数定义几乎应该始终位于脚本的顶层。