首页 > 解决方案 > 问题创建将数据提交到数据库并发送电子邮件的组合 PHP 脚本

问题描述

对 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";

    }


?>

标签: phphtmlmysqlemail

解决方案


您的查询中包含参数,您不能将其与$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) ){

||如果任何输入都已填写,&&则为真,如果所有输入都已填写,则为真。

另一个问题是你有块的定义check_input()和块show_error()内部ifif这意味着在执行并且条件成功之前不会定义函数。但是你在 之前调用它们if,所以你应该得到关于未定义函数的错误。函数定义应该几乎总是在脚本的顶层。


推荐阅读