PHP/MySql Varibale Not being Set

PHP/MySql Varibale Not being Set
0

#1

Hi, everyone. I’m having some issues with this code. Before I added mySQL, it worked fine, but now that I’ve added it, it seems the $msg varibale isn’ being set because no message is displayed even though the mail function executes (because I receive the email) and the information is saved in the database. Literally the only thing not happening is the variable being set and I just can’t see why. Any help would be greatly appreciated.

<?php 
require("./config/db.php");

$msg = "";

if (filter_has_var(INPUT_POST, "submit")) {
  $name = htmlspecialchars($_POST["name"]);
  $email = htmlspecialchars($_POST["email"]);
  $message = htmlentities($_POST["message"]);

  if (!empty($name) && !empty($email) && !empty($message)) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL === false)) {
      $msg = "Merci de revérifier votre email";
    } else {
      $toEmail = "[email protected]";
      $subject = "Contact Form";
      $body = "<h2>Contact form submitted</h2>
      <h4>Name</h4><p>$name</p>
      <h4>Email</h4><p>$email</p>
      <h4>Message</h4><p>$message</p>";

      $header = "MIME-Version: 1.0" . "\r\n";
      $header .= "Content-Type:text/html;charset=UTF-8" . "\r\n";
      $header .= "From: " . $name . "<" . $email . ">" . "\r\n";

      if (mail($toEmail, $subject, $body, $header)) {
        $msg = "Votre email a été enovyé sans problème!";
        
        $sqlName = mysqli_real_escape_string($conn, $_POST["name"]);
        $sqlEmail = mysqli_real_escape_string($conn, $_POST["email"]);
        $sqlMessage = mysqli_real_escape_string($conn, $_POST["message"]);

        $query = "INSERT INTO submissions(name, email, message) VALUES('$sqlName', '$sqlEmail', '$sqlMessage')";

        if (mysqli_query($conn, $query)) {
          header("Location: " . ROOT_URL . "");
        } else {
          echo "ERROR: " . mysqli_error($conn);
        }
      }
    }
  } else {
    $msg = "Merci de remplir tout le formulaire";
  }


}

?>

#2

Does $msg get set if $name is empty?


#3

It does indeed. Does that have any effect?


#4

To be specific, it gets the value: “Merci de remplir tout le formulaire”


#5

Found the problem!

It was these lines:

if (mysqli_query($conn, $query)) {
          header("Location: " . ROOT_URL . "");
        } else {
          echo "ERROR: " . mysqli_error($conn);
        }

I’m really new to PHP and MySql but I think it was reloading the page and then resetting $msg a second time with no POST information so it got set to blank. Thanks for your nudge!