订阅表单不会向数据库发送信息

时间:2018-01-03 22:48:01

标签: php mysql forms insert subscribe

我有一个订阅表单,只有两个文本框用于姓名和电子邮件。我希望这些信息存储在MySql数据库中。提交表单时,我可以连接到数据库,但不会发送信息。这是表单的代码(只是感兴趣的部分):

<div class="jumbotron text-center">
  <h1>Community Garden</h1>
  <p>We are a local community that
  grows organic vegetables and fruit</p>
  <img src="Front.jpg" class="img-rounded" alt="front" > <br><br>
  <form class="form-inline" action="news.php" method="post'>
    <div class="input-group">
      <input type="text" name="name" class="form-control" size="50" placeholder="Name" required> 
      <input type="text" name="email" class="form-control" size="50" placeholder="Email Address" required>
     <br><br> <div class="input-group-btn">
        <button type="submit" name="submit" value="submit" class="btn btn-danger">Subscribe</button>
      </div>
    </div>
  </form>
</div>

这是用于数据库连接和信息存储的php脚本。该文件名为news.php。 非常感谢任何帮助。

<?php
//include database connection details
$username = "root";
$password = "password";
$hostname = "127.0.0.1"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
 or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with
$selected = mysql_select_db("Community Garden List",$dbhandle) 
  or die("Could not select examples");

if(isset($_POST['submit'])){

//collect data from form and remove any tags and make safe for database entry
$name = strip_tags(mysql_real_escape_string($_POST['name']));
$email = strip_tags(mysql_real_escape_string($_POST['email']));

//check name lengh
if (strlen($name) < 3) {
    $error[] = 'Name must be more then 3 characters.';
}

//if name is equal to name then give an error
if ($name == 'Name') {
    $error[] = 'Please enter your name.';
}

// check for valid email address
$error = "";
$pattern = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($pattern, trim($email))) {
    $error[] = 'Please enter a valid email address';
}

// if validation is okay then carry on
if (!$error ) {

//insert into database
$sql = mysql_query("INSERT INTO newsletter (name,email) VALUES ('$name','$email')")or die(mysql_error());

//submission successful show a message
echo "<p>Thank you, submission was successful.</p>";

} // end validation
}// end submit

//show any errors
if (!empty($error))
{
        $i = 0;
        while ($i < count($error)){
        echo '<div class="msg-error">".$error[$i]."</div>';
        $i ++;}
}// close if empty errors

?>

2 个答案:

答案 0 :(得分:0)

您的开场<form>标记是否格式不正确?

具体方法部分:

 method="post'

查看开场报价是如何加倍,但结束报价是单一的。 W3C验证程序无法验证此类表单标记。考虑到这一点,浏览器可能会忽略此属性并使用默认方法(即GET)提交表单。 (或者它可能只是完全忽略了<form>。)

您可以在此处验证您的HTML:http://validator.w3.org/

答案 1 :(得分:0)

您基本上没有运行$sql。要在数据库中插入,您应该删除$sql=部分。 在您的代码中,您只需使用$sql变量来存储查询。