Ajax表单数据到达.done(函数(数据)),但没有数据发布到数据库



我在数据库中发布信息时遇到一些问题。我有其他信息通过javascript中的ajax调用发布到我的数据库中,它发布没有问题,但是,我不知道我的这部分代码出了什么问题。它拒绝发布到数据库。我想把它发布出来,看看是否有人发现了我没有发现的东西,这会阻止它进入数据库。有趣的是,ajax调用在我的.done function(data)中进行ajax调用,但没有任何东西进入我的数据库。

下面我已经发布了所有代码,我认为是相关的

$('#form-reg').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type        : 'POST',
url         : 'register.php',
data        : formData,
success: function(data){
console.log(data),
},
error: function(err){ console.log(err)
};
})
.done(function (data) {
console.log("lo");
document.getElementById('form-reg').reset(function(){
alert("signed  up completed");
});
})
.fail(function (error) {
alert("POST failed");
});
return false;
});
/*mysqli_connect.php -- note this is just an old file name. not important*/
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
/*register.php*/
<?php
require 'mysqli_connect.php';
if((isset($_POST['name']) && !empty($_POST['name']))||
(isset($_POST['email']) && !empty($_POST['email']))){
$sth = $dbh->prepare('INSERT INTO test_table (comment) VALUES(?,?);');
$name = $_POST['name'];
$email = $_POST['email'];
$sth->execute(Array($name, $email));
}
else{
echo 'error no comment entered';
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<div id = "register-container">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
</div>

如果我错过了什么,请随意请求那段代码。

似乎问题出在:

INSERT INTO test_table (comment) VALUES(?,?);

为什么有一个col"(comment(",而在VALUES中有两个(?,?(占位符?表"test_table"中有哪些列?我认为查询可能类似于:

INSERT INTO test_table (name, email) VALUES(?,?);

我认为你的问题在于你的PHP。

$sth = $dbh->prepare('INSERT INTO test_table (comment) VALUES(?,?);');
$name = $_POST['name'];
$email = $_POST['email'];

您的SQL不知道问号(?(是什么,除非您给它们一个值。看看下面的例子:

$name = $_POST['name'];
$email = $_POST['email'];
$sth = $dbh->prepare('INSERT INTO test_table VALUES(?,?);');
$sth->bind_param('ss', $name, $email); // you must bind the values you wish to insert
$sth->execute();

有关bind_param的更多信息,请参阅PHP文档:http://php.net/manual/en/mysqli-stmt.bind-param.php

最新更新