0

Pretty new to PHP, Ive been trying to combine to working codes into a single function but have not had any success. After spending all day trying to tweak it to get it to work ive decided to ask for guidance and help

Ive tried restructuring the code order but no success.

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


?>

Any help would be deeply appreciated.

Below is the code after applying the changes that Barmar suggested, still not being able to make this work though. (this now includes the relocation of the function scripts)


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

    }


?>

smartinez
  • 1
  • 1

1 Answers1

0

Your query has parameters in it, you can't use it with $conn->query(). Change:

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

to

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

You also echo that the record was inserted successfully even if executing the query gets an error. You should use:

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

Your test that all the input fields were provided is wrong.

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

should be

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

|| is true if any of the inputs are filled in, && is true if all are filled in.

Another problem is that you have the definitions of check_input() and show_error() inside the if block. That means the functions won't be defined until the if is executed and the condition succeeds. But you're calling them before the if, so you should be getting errors about undefined functions. Function definitions should almost always be at the top-level of the script.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I updated the code above with the suggested modifications. This still isnt able to successfully complete the process. – smartinez Jul 15 '19 at 15:00
  • You have function definitions inside the `if`. Move them to the top level of the script. – Barmar Jul 15 '19 at 15:12
  • Marbar I apologize for that ive realocated it but still no luck. Is there something im missing in how the code is being compiled that is causing the error? ive ran it through some online checkers and these generate no errors. – smartinez Jul 15 '19 at 15:59
  • Marbar looking at the code I noticed a typo in the table name, this is now working as intended thank and everyone else for all the help. – smartinez Jul 15 '19 at 17:06
  • I spoke too soon it seems to be creating a duplicate entry in the database, but single subsmision to email. – smartinez Jul 15 '19 at 17:14
  • You're calling `$stmt->execute()` twice. You do `$stmt->execute()` and then `if ($stmt->execute())`. Get rid of the first one. – Barmar Jul 15 '19 at 17:48
  • Commented out: $stmt->execute(); , i didnt realize this would execute without it being stated in a single line item. – smartinez Jul 15 '19 at 17:58
  • Thanks Marbar do you know of any tricks on how to mask the default address the email is sent from. id like to have a clean address and not one including the full server name. – smartinez Jul 15 '19 at 18:00
  • Why do you keep writing Marbar instead of Barmar? – Barmar Jul 15 '19 at 18:06
  • Put a `From: yourname@yourdomain.com` header in the headers argument to `mail()`. – Barmar Jul 15 '19 at 18:07
  • I apologize for the name I must of misread and it stuck in my head. You have been extremely helpful. – smartinez Jul 15 '19 at 18:36