Peter Pik Peter Pik - 6 months ago 8
SQL Question

Post request data is not being inserted into mysql

I've made below post request, which seem to work fine. when i look in developer tools under network everything seem to work and i can see that each parameter is being posted. however when the

insert.php
is executed nothing is added to the database and i'm not receiving any error message. I'm trying to save the image into a Blob in mysql.

post request

var description = $('#description').val();
var title = $('#title').val();

var fileInput = $("#image")[0];
var file = fileInput.files[0];
var dataResult = new FormData();
dataResult.append('image', file);
dataResult.append('desc', description);
dataResult.append('title', title);
dataResult.append('longitude', currentMarker.lng());
dataResult.append('latitude', currentMarker.lat());

$.ajax({
type: 'POST',
url: 'insert.php',
data: dataResult,
processData: false,
contentType: false,
success: function (answer) {

}
})


insert.php

include('config.php');

if (isset($_POST['title']) && isset($_POST['body']) && isset($_POST['longitude']) && isset($_POST['latitude'])){
$title = $_POST['title'];
$body = $_POST['body'];
$longitude = (float)$_POST['longitude'];
$latitude = (float)$_POST['latitude'];
$file = file_get_contents($_FILES['image']['name']);


$strSQL = $db->query("INSERT INTO camps (title, body, longitude, latitude, image) VALUES ('$title', '$body', '$longitude','$latitude', '$file')");


}


Dump

array(4) {
["desc"]=>
string(6) "teeest"
["title"]=>
string(11) "test"
["longitude"]=>
string(18) "-74.17870044708252"
["latitude"]=>
string(17) "40.73480350827126"
}

Answer

There are a few problems here:

  1. There is no output of the script, nor any error handling and when you get the output back in the answer variable, you don't do anything with it. You should at least dump that to the console to see what is happening.
  2. You will never enter your if block as there is no element with a key of body
  3. The path to your file is not $_FILES['image']['name'] but $_FILES['image']['tmp_name'].
  4. You have an sql injection problem. You should use a prepared statement with bound variables instead of injecting your variables directly in the query.

There may be more but when you add error handling and use the output of the script, you will at least be able to see what is wrong exactly.

Apart from that I would recommend that you store the file as a file in the file-system and just add the path to the database.