【发布时间】:2013-03-02 21:10:00
【问题描述】:
我正在创建一个评论表单,它将询问用户他的姓名、电子邮件并使用 php 和 mysqli 发表评论以连接到数据库和 jquery 以不刷新,但问题是: 我无法将数据插入数据库,但是当我“回显”保存从用户输入的数据的变量时,它可以在不输入数据库的情况下正常工作,我不知道错误是什么。
谁能帮帮我?
ps:我不是要求为我编写代码,但我需要知道如何解决它。
submit_to_db.php
<?php
$conn = new mysqli('localhost', 'root', 'root', 'my_db');
if(isset($_POST['submit'])){
$name =isset ($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
echo"<pre>";
print_r($_POST);
echo"</pre>";
$query = "INSERT into comments('email', 'comments') VALUES(?, ?)";
echo $query;
$stmt = $conn->stmt_init();
if($stmt->prepare($query)){
$stmt->bind_param('ss', $email, $comments);
$stmt->execute();
//var_dump($stmt);
}
if($stmt){
echo "thank you .we will be in touch soon <br />";
// echo $_POST['name'];
//echo $_POST['email'];
//echo $_POST['comments'];
var_dump($stmt);
}
else{
echo "there was an error. try again later.";
}
}
else
echo"it is a big error";
?>
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>feedback page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel ="stylesheet" href = "css/default.css" />
<script type = "text/javascript">
$(function(){
$('#submit').click(function(){
$('#container').append('<img src = "img/loading.gif" alt="Currently loading" id = "loading" />');
var name = $('#name').val();
var email = $('#email').val();
var comments = $('#comments').val();
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: 'name =' + name + '&email=' + email + '&comments=' + comments,
success: function(result){
$('#response').remove();
$('#container').append('<p id = "response">' + result + '</p>');
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
});
});
</script>
</head>
<body>
<form action = "submit_to_db.php" method = "post">
<div id = "container">
<label for = "name">Name</label>
<input type = "text" name = "name" id = "name" />
<label for = "email">Email address</label>
<input type = "text" name = "email" id = "email" />
<label for = "comments">Comments</label>
<textarea rows = "5"cols = "35" name = "comments" id = "comments"></textarea>
<br />
<input type = "submit" name = "submit" id = "submit" value = "send feedBack" />
</div>
</form>
</body>
</html>
【问题讨论】:
-
你在代码中输入的 var_dump 的输出是什么?
-
我从第一个得到错误,如果这意味着来自 if (isset($_POST['submit'])){...} 但如果我删除第一个 if 语句我得到这个 谢谢。我们将尽快与您联系 object(mysqli_stmt)[2] public 'affected_rows' => null public 'insert_id' => null public 'num_rows' => null public 'param_count' => null public 'field_count' = > null public 'errno' => null public 'error' => null public 'error_list' => null public 'sqlstate' => null public 'id' => null
-
此代码与 OP 在另一个问题中的帖子相似/相同。我在我的服务器上安装了脚本,它们确实可以工作。
标签: php mysql ajax jquery mysqli