我正在创建一个简单的表单评论,允许用户使用 php mysql jquery 发送评论并插入到数据库中,以便在页面中不刷新一切正常,但问题是:当我写评论时,mysql 数据库需要 4 行并在其中填写相同的数据有人可以帮助我解决错误吗?
my_db.sql
--
-- Database: `my_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `comments`
--
CREATE TABLE IF NOT EXISTS `comments` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(70) NOT NULL,
`comments` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `comments`
--
INSERT INTO `comments` (`id`, `name`, `email`, `comments`) VALUES
(1, 'test', 'test@test.com', 'testcomments'),
(2, 'test', 'test@test.com', 'testcomments'),
(3, 'test', 'test@test.com', 'testcomments'),
(4, 'test', 'test@test.com', 'testcomments');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
index.php // jquery的表单和函数在哪里
<!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>
</div>
</body>
</html>
submit_to_db.php
<?php
$conn = new mysqli('localhost', 'root', 'root', 'my_db');
$query = "INSERT into comments(name, email, comments) VALUES(?, ?, ?)";
$stmt = $conn->stmt_init();
if($stmt->prepare($query)){
$stmt->bind_param('sss', $_POST['name'], $_POST['email'], $_POST['comments']);
$stmt->execute();
}
if($stmt){
echo "thank you .we will be in touch soon";
}
else{
echo "there was an error. try again later.";
}
?>