I am trying to insert the data like this
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);
});
}
});
}
<?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";
?>
The issue is I am getting error on $mysqli->query($insert);
that 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
What should I do to make it run. I have tried everything but could not find any working solution. Please Help!! Thanks in advance
There are some string
values. You need to use the '
s properly.
VALUES ('" .implode("','",$data)."')"
Explanation
The code you are using is generating something like - VALUES ('name, email, phone, message')
which is wrong in syntax. They all are string
s and need to wrapped in '
s.
('" . implode("', '", $data) . "')
- will wrap them up properly. It will generate - VALUES ('name', 'email', 'phone', 'message')
Try this:
$postdata = implode("','", $data) ;
$insert = "INSERT INTO contact(Name,Email,Phone,Message) VALUES ('$postdata')";
The function implode will Join array elements with a string. Now your function is implode(",",$data)
that will make the string something like this
NameData,EmailData,PhoneData,MessageData
Whereas you will be looking to make it like this
'NameData','EmailData','PhoneData','MessageData'
So to do that you need to make your implode function looks like this implode("','",$data)
and the first and last '
s is already coming in from the code you have written.