我有一个订阅表,只有两个文本框的名称和电子邮件。我希望这些信息存储在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条答案
按热度按时间vyu0f0g11#
你基本上不跑了
$sql
. 为了在数据库中插入,您应该删除$sql=
部分。在代码中,您只是使用$sql
变量来存储查询。yduiuuwa2#
是你的开场白吗
<form>
标签格式不正确?具体方法部分:
看看开头的引号是双引号,而结尾的引号是单引号。w3c验证程序无法验证这样的表单标记。考虑到这一点,浏览器可能会忽略此属性,并使用默认方法get提交表单(或者完全忽略了
<form>
.)您可以在此处验证您的html:http://validator.w3.org/