联系表单会发送电子邮件,但不会在数据库中插入条目

时间:2014-10-20 06:12:47

标签: php sql regex

提交联系表单时,它会发送电子邮件,但不会在数据库中插入条目。我有基本的PHP知识,但我不是很擅长PHP所以请明确。我在db中创建了db,db user和table,并创建了我尝试将值放入的所有字段,但它没有在db中插入条目。提交表单时也不会显示任何错误消息。提前谢谢。

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

2 个答案:

答案 0 :(得分:0)

将CURRENT_TIMESTAMP更改为NOW()。

答案 1 :(得分:0)

将您的查询更改为

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

无需发送 ID (如果自动增量)。 CURRENT_TIMESTAMP也是常量,因此请使用NOW()来获取当前时间。

注意: - mysql_*已被弃用,使用mysqli_*PDO