2

I am trying to add an image in to my database with two columns, name and id. However when I tried the code below only the id is inserted but not the image. Please tell me where I need to correct the code.

$(function() {
  $('#insert').click(function() {
    var file = $('#image').val();
    $.ajax({
      url: "addimg.php",
      method: "post",
      async: false,
      data: {
        "insert": 1,
        file: file
      },
      success: function(data) {
        $('#image').val('');
      }
    })
  });
});
<input type="file" name="myfile" id="image">
<input type="submit" name="insert" id="insert">
<?php
  $conn = mysqli_connect('*****', '****', '*****', '*****');
  if (isset($_POST['insert']))
  {
    $file = addslashes(file_get_contents($_FILES["myfile"]["tmp_name"]));
    $query = "INSERT INTO tbl_images(name) VALUES('$file')";
    mysqli_query($conn, $query);
  }
?>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sami Kahsay
  • 39
  • 1
  • 1
  • 5
  • mybe changing the param `method` by `type:"post"` inside the ajax? – Roy Bogado Apr 09 '19 at 08:56
  • 5
    Firstly, when sending binary data in an AJAX request you need to use a FormData object, like [this](https://stackoverflow.com/a/29792182/519413), and you need to set `contentType` and `processData` to `false`. Secondly, as `image` is binary data you either need to store it as a BLOB in your mySql database, or convert it to base64 and save it as a string. Lastly, never use `async: false` in an AJAX request, it's incredibly bad practice. – Rory McCrossan Apr 09 '19 at 09:00
  • either you convert to base64 or save the file to a directory and add the path to database – jobinrjohnson Apr 09 '19 at 09:01
  • You can find lots of working examples of this process online already – ADyson Apr 09 '19 at 09:06
  • 1
    Avoid storing image as a blob in database,It may slow the query execution,Try storing it in folder instead – Deepak A Apr 09 '19 at 09:21

2 Answers2

1

Set the image field as blob in mysql before following my code,Hope this helps ,thanks

HTML CODE

<input type="file" name="myfile" id="image">
<input type="submit" name="insert" id="insert">

In Js

$(function() {
      $('#insert').click(function() {
        var file = $('#image').prop("files")[0];  
        var form_data = new FormData();  
        form_data.append("file", file)  
        form_data.append("insert", '1') 
        $.ajax({
          url: "addimg.php",
          method: "post",
          async: false,
          data:form_data,
          cache: false,
          contentType: false,
          processData: false,
          success: function(data) {
            $('#image').val('');
          }
        })
      });
    });

in Php

<?php

  if (isset($_POST['insert']))
  {
    if(isset($_FILES["file"])){

    // Find location of uploaded file
    $tmpName = $_FILES["file"]["tmp_name"];

    // Read data
    $fileHandle = fopen($tmpName, "r");
    $image = fread($fileHandle, filesize($tmpName));
    fclose($fileHandle);

    // Run query
    $db = mysqli_connect("xxxx","xxx","xxx","xxx"); 
    $query = "INSERT INTO tbl_images(name) VALUES('$image')"; 
    $qry = mysqli_query($db, $query);
  }
  }
?>

Refer BLOB: Storing Images using PHP inside MySQL Database

/*don't store images in a database ever*/

Alternate Solution ,

<?php
 $path = 'path/to/folder';
 $file_name = $_FILES['file']['name'];
 $file_tmp  = $_FILES['file']['tmp_name'];
 if (file_exists($path)) {                                             
              move_uploaded_file($file_tmp,$path.$file_name);

 } else {
    mkdir($path, 0755);                              
    move_uploaded_file($file_tmp,$path.$file_name);                                            
  }
    $path = $path.$file_name;
    $db = mysqli_connect("xxxx","xxx","xxx","xxx"); 
    $query = "INSERT INTO tbl_images(name) VALUES('$path')"; //Store image path instead
    $qry = mysqli_query($db, $query);
?>
Deepak A
  • 1,624
  • 1
  • 7
  • 16
0

You want to send multipart/form-data in ajax. So you have to send data as an object of FormData. This will post all input values (including files) of the given form (form_id is the id of your form) to the server. On server end you can get posted data in $_POST and files in $_FILES

$(function() {
  $('#insert').click(function() {
    var formdata = new FormData($('#form_id')[0]);
      $.ajax({
            url: "addimg.php",
            type: 'POST',
            dataType: 'json',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            data: formdata,
            success: function (response) {
               [ Reset your form here... ]
            }
        });
      });
});
Alok Mali
  • 2,821
  • 2
  • 16
  • 32