2014-11-08 49 views
1

由于某种原因,我无法让我的表单插入到数据库中。我已经使用不同的方法重写了3次,似乎无法使其工作。希望有人能帮助我在现场。这是我的html代码。从表单插入数据库不插入,但没有产生错误

<?php 
include_once 'layout/header.php'; 
?> 

<!DOCTYPE html> 
<html lang="en"> 

<div class= "jumbotron"></div> 
<body> 

<form action="send_form_email.php" method = "POST"/> 
<p> First Name: <input type="text" name="first_name" maxlength="50" size="30"/></p> 
<p> Last Name: <input type="text" name="last_name" maxlength="50" size="30"/></p> 
<p> Email:<input type="text" name="email"  maxlength="80" size="30"/></p> 
<p> Telephone: <input type="text" name="telephone" maxlength="12" size="30"/></p> 
<p> Comments: <textarea name="comments" maxlength="1000" cols="32" rows="6"></textarea></p> 
<br> 
<input type="submit" value="Submit"> 
<br> 
</br> 

</form> 
</body> 
</html> 
<?php include_once 'layout/footer.php'; ?> 

这里是PHP代码。

<?php 
include_once 'layout/header.php'; 
include_once 'db_function.php'; 
include_once 'helpers/helper.php'; 
session_start(); 

$DB_HOST = 'localhost'; 
$DB_USER = 'Chris'; 
$DB_PASSWORD = 'Uraloser82'; 
$DB_NAME = 'newsite'; 
$conn = mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME); 


$first_name = $_POST['first_name']; 
$last_name = $_POST['last_name']; 
$email = $_POST['email']; 
$telephone = $_POST['telephone']; 
$comments = $_POST['comments']; 

$query = "INSERT INTO contact(first_name, last_name, email, telephone, comments) VALUES ('$first_name', '$last_name', '$email', '$telephone', '$comments')"; 
?> 

<h4>Thank you for contacting Plank's Brickyard we will get back to you very soon!</h4> 

<img class= "gamer" src= "assets/uploads/gamer.jpg"> 
<?php include_once 'layout/footer.php'; ?> 
+0

请理解您的代码容易受到SQL注入攻击。 – 2014-11-08 04:17:39

回答

2

数据未插入的原因是您不是querying

加入执行以下操作/使用mysqli_query()

$query = mysqli_query($conn, "INSERT INTO contact ... 

的改写:

$query = mysqli_query($conn, "INSERT INTO contact 
(first_name, last_name, email, telephone, comments) 
VALUES ('$first_name', '$last_name', '$email', '$telephone', '$comments')") 

     or die(mysqli_error($conn)); 

使用or die(mysqli_error($conn))赶上DB错误,应该任何存在。

有关功能的更多信息,请访问:

另外,您的本次代码是开放的SQL injection
使用prepared statementsPDO with prepared statements

+0

这工作!谢谢,这是我的第一个基于html/PHP的网站,所以我不知道你和上一张海报提到的注入攻击。我会考虑重新工作。谢谢 – planker1010 2014-11-08 04:16:27

+0

@ planker1010你很受欢迎。注射攻击预防非常重要。准备好陈述的PDO进行得相当顺利,这是我个人的偏好。 *干杯* – 2014-11-08 13:38:44

1

看起来你好像缺少$conn->query($query);。此外,您还需要通过转义输入来保护自己免受SQL注入攻击。示例$first_name = $conn->real_escape_string($_POST['first_name']);如果您仍然遇到问题,请尝试回显您的查询,然后在phpmyadmin中运行它。

+0

我添加了缺少的$ conn-> query($ query)并得到了2个错误。所以我重复了一遍,结果对于表单中输入的内容是正确的。第一个错误告诉我新添加的代码是“未定义的”。第二个错误是空的querey? – planker1010 2014-11-08 04:14:10

+0

将'$ conn'的声明更改为'$ conn = new mysqli($ DB_HOST,$ DB_USER,$ DB_PASSWORD,$ DB_NAME);'并且它应该使用面向对象的方法。有关详细信息,请参见[php手册mysqli查询](http://php.net/manual/en/mysqli.query.php)。 – 2014-11-08 04:22:47

+0

我应该坚持你的程序方法,在我的答案是'mysqli_query($ conn,$ query);' – 2014-11-08 04:28:24

相关问题