【发布时间】:2015-11-13 13:52:05
【问题描述】:
我正在尝试像这样插入数据
function submitData() {
//Posting to ContactDB with JSON format
$.post("contactDB.php",
JSON.stringify({
name: $("#name").val(),
email: $("#email").val(),
phone: $("#phone").val(),
message: $("#message").val()
}),
function(usrava){
// if data is inserted successfully than show insert success message in Result div
if(usrava=='Data Inserted')
{
$("#result").fadeTo(200,0.1,function(){
$(this).html('Your message is successfully saved with us. We will get back to you soon.').fadeTo(900,1);
});
}
//else show the error
else
{
$("#result").fadeTo(200,0.1,function(){
$(this).html(usrava).fadeTo(900,1);
});
}
});
}
ContactDB.php
<?php
$mysqli = new mysqli("localhost", "root", "", "contactDB"); //Connection to the Database
//If Error than die
if (mysqli_connect_errno()) {
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
//Echo for the response
echo "Data base connection NOT Successful. Please get the assistance from your Administrator.";
//Should not go out if not connected
exit();
}
//data received in json. decoded it to an array
$data = json_decode(file_get_contents('php://input'), true);
//Create a insert Command using implode as the data is already in the array
$insert = "INSERT INTO contact(Name,Email,Phone,Message) VALUES ('" .implode(",",$data)."')";
$mysqli->query($insert);
//Close the connection
$mysqli->close();
// Echo for the response
echo "Data Inserted";
?>
问题是我在$mysqli->query($insert); 上遇到错误You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near Rajesh, at line 1
我应该怎么做才能让它运行。我已经尝试了一切,但找不到任何可行的解决方案。请帮忙!!提前致谢
【问题讨论】:
-
回显 $insert,我猜语法不正确,好的,检查你的#result div 它显示的内容
-
$data 已经是一个关联数组,因此使用 implode 会生成一个与您想的不同的字符串,只需在执行查询之前 print_r() $data,您会发现它不是按照SQL 语法
标签: php jquery mysql ajax json