I have a array containing objects and I want to store these objects into my MySQL DB. At the beginning it worked quite fine, but suddenly it stopped working even though it did not make any changes to the code or the DB.
The array of object looks as follows: var geocoded = [{zip: 1234, place: "XY", country: "XY", lat: "123.123", lng: "123.123"}, ...];
I use the following JS code to iterate over the array and post each object to the DB. kiter is the iterator I use and is defined as geocoded.length - 1
function postPlaces(data, kiter) {
if (kiter >= 0) {
$.post("api/placessave.php",
data[kiter],
function(data, status){
kiter--;
postPlaces(geocoded, kiter);
console.log(data + '.............' + status);
}
);
} else {
//statusUpdate(id);
}
}
placessave.php looks as follows:
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','*****');
define('DB','****');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$zip = $_POST['zip'];
$place = $_POST['place'];
$country = $_POST['country'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
if(mysqli_query($con, $sql)){
echo "success";
}
mysqli_close($con);
?>
I use INSERT IGNORE because duplicates may exist but an update is not needed. The interesting part is, that everything works quite nice I also get a Success on every query but nothing is stored to the DB.
Insert Query you have to change like this. You have Missed Quotes around the values
Replace
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
With
$sql = "insert ignore into places (zip, place, country, lat, lng) values ('".$zip."', '".$place."', '".$country."', '".$lat."', '".$lng."')";
I found the solution myself. The problem was in the data I wanted to store. I found that there was a place name which contained a '
. Therefore the query did not work. After removing this, everything works fine.
just change ($zip,
in the query to ('$zip',
zip
is probably string and you are not passing it as string in the query. Moreover, this code is vulnerable to SQL injection. Please read about it to avoid insecurities.