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);
  }
?>
5
  • mybe changing the param method by type:"post" inside the ajax? Commented Apr 9, 2019 at 8:56
  • 5
    Firstly, when sending binary data in an AJAX request you need to use a FormData object, like this, 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. Commented Apr 9, 2019 at 9:00
  • either you convert to base64 or save the file to a directory and add the path to database Commented Apr 9, 2019 at 9:01
  • You can find lots of working examples of this process online already Commented Apr 9, 2019 at 9:06
  • 1
    Avoid storing image as a blob in database,It may slow the query execution,Try storing it in folder instead Commented Apr 9, 2019 at 9:21

2 Answers 2

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);
?>
Sign up to request clarification or add additional context in comments.

Comments

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... ]
            }
        });
      });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.