Home » Javascript » File upload to DB using Ajax and PHP

File upload to DB using Ajax and PHP

Posted by: admin August 19, 2018 Leave a comment

Questions:

Im looking for help here. Cant figure it out where is problem here. Im trying to make multiple file upload to database using Ajax and PHP. I am getting this error:

Warning: file_get_contents(iamge.png): failed to open stream: No such
file or directory in /var/www/html/includes/forms/addProductSteps/BTR/upload.php on line 12

Can you please check code below:

index.php:

<form id="fourthStepForm" class="" action="" method="post" enctype="multipart/form-data">
  <input type="file" multiple id="imagesToUpload" name="files[]" value="">
  <div class="col-xs-3 col-md-3"><input type="submit"  onclick="fourthStep();return false" name="submit" value="Finalize" class="btn btn-primary btn-block btn-md" tabindex="5"></div>
</form>

function fourthStep(){

var formData = new FormData();
var ins = document.getElementById('imagesToUpload').files.length;
for (var x = 0; x < ins; x++) {
    formData.append("files[]", 
    document.getElementById('imagesToUpload').files[x]);
}

$.ajax({
    url: 'includes/forms/addProductSteps/BTR/upload.php',
    dataType: 'text',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    type: 'post',
    success: function (response) {
        alert(response);
    },
    error: function (response) {
        alert(response);
    }
});
}

upload.php:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include_once'../../../connections_multi.php';
$p_id = 1001; //for testing purpose

$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
   if ($_FILES["files"]["error"][$i] > 0) {
      echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
   } else {
    $file = addslashes(file_get_contents($_FILES["files"]["name"][$i]));
    if (!($stmt = $db->prepare("INSERT INTO products.battery_lobs ( p_id,img) VALUES (?,?)"))) {
      $response = $stmt->error;
    }
    if (!$stmt->bind_param("sb", $p_id, $file )) {
      $response = $stmt->error;
    }
    if (!$stmt->execute()) {
      $response = $stmt->error;
    }else{
      $response = "true";
    }
  }
}

echo $response;

and $response i get here is “true”. So data is inserted but BLOB is 0 bytes. No image.

Thanks!

Answers: