php + mysql插入错误

我正在创建一个简单的表单注释,将允许用户使用php mysql jquery发送注释和inserti进入数据库,在页面中没有刷新所有工作正常但问题是:当我写我评论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的forms和function

     feedback page    $(function(){ $('#submit').click(function(){ $('#container').append('Currently 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('

' + result + '

'); $('#loading').fadeOut(500, function(){ $(this).remove(); }); } }); return false; }); });

submit_to_db.php

 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."; } ?> 

我实际上把你的脚本,加载到我的服务器上,创建数据库表,并测试脚本。

每次提交只插入一行。

您的脚本运行正常。

但是,您的测试程序存在缺陷。

我还检查了Firebug控制台,AJAX调用按预期工作。

除非你有其他诊断,否则我认为我不能再帮你了。

错误警报
你的代码中有一个错误会导致你未来几年的生活中充满悲伤……

 if($stmt){ echo "thank you .we will be in touch soon"; } else{ echo "there was an error. try again later."; } 

自执行查询以来,此if语句将始终求值为true(当然,除非MySQL未运行)。

您的意图是查看插入是否成功,为此,您需要检查:

 if($stmt->affected_rows){...} 

$stmt->affected_rows将在失败时返回-1,或在成功时返回+1。

调试策略
(1)在您的时间戳中添加一个额外的字段,以便您可以看到插入记录的时间。 这将使您更深入地了解正在发生的事情。

(2)清空你的桌子并再次尝试你的代码。 您可能认为您正在获得多个插入,但也可能是您按下提交按钮4次。