Monday 3 September 2018

PHP The contact form sends an e-mail but does not enter an entry in the database

When submit contact form it sends email but does not insert entry in database. I have basic knowledge of php but I am not very good at php so please be clear. I have created db, db user and table in db and created all fields which I am trying to put values in, but it does not insert entry in the db. Also it does not show any error message when submit the form. Thank you in advance.

    <?php
$errors = '';
$myemail = 'myEmailaddress@hotmail.com';
if(empty($_POST['cname'])  ||
    empty($_POST['email']) ||
    empty($_POST['website']) ||
    empty($_POST['subject']) ||
    empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}

$name = $_POST['cname'];
$email_address = $_POST['email'];
$website = $_POST['website'];
$subject = $_POST['subject'];
$message = $_POST['message']; 

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
    $to = $myemail;
    $email_subject = "Contact form submission: $name";
    $email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Subject: $subject \n Website: $website \n Message: $message"; 

    $headers = "From: $myemail\n";
    $headers .= "Reply-To: $email_address";

    mail($to,$email_subject,$email_body,$headers);

    //starting sql query code here

if( $_POST )
{
  $con = mysql_connect("localhost","db-username","password");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("db-name", $con);

  $name = mysql_real_escape_string($name);
  $email_address = mysql_real_escape_string($email_address);
  $website = mysql_real_escape_string($website);
  $subject = mysql_real_escape_string($subject);
  $message = mysql_real_escape_string($message);

  $query = "
  INSERT INTO `db_name`.`table_name` (`id`, `cname`, `email`, `website`,
        `subject`, `message`, `timestamp`) VALUES (NULL, '$name',
        '$email_address', '$website', '$subject', '$message',
        CURRENT_TIMESTAMP);";

  mysql_query($query);

//  echo "<h2>Thank you for your Comment!</h2>";

  mysql_close($con);
}

//ending sql query code here

    //redirect to the 'thank you' page
    header('Location: thankyou.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>

</body>
</html>


Change CURRENT_TIMESTAMP to NOW().

0 comments:

Post a Comment