我正在尝试像这样插入数据
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);
上遇到错误,你的 SQL 语法有错误;查看与您的 MySQL 服务器版本对应的手册,了解在 Rajesh 附近使用的正确语法,第 1 行
我应该怎么做才能让它运行。我已经尝试了一切,但找不到任何可行的解决方案。请帮忙!!提前致谢
最佳答案
有一些 string
值。您需要正确使用 的
。
VALUES ('" .implode("','",$data)."')"
解释
您正在使用的代码生成类似 - VALUES ('name, email, phone, message')
的语法错误。它们都是字符串
,需要用包裹。
('". implode("', '", $data) . "')
- 将正确地包装它们。它将生成 - VALUES ('name', 'email', 'phone', 'message')
关于php - 使用 JSON 插入时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109474/