Help to upload an image to a phpmyadmin database with AJAX

1

Good morning, I have a problem uploading an image to my database. I have several different data and all are saved except the image, which I configured with the column name "IMG" and longblob file type

This is my HTML:

<div class="control-group">
              <div class="form-group floating-label-form-group controls">
                <label>Fotos del platillo</label>
                <input type="file" name="IMG" class="form-control" placeholder="Fotos del platillo" id="IMG" required data-validation-required-message="Debes rellenar este espacio.">
                <p class="help-block text-danger"></p>
              </div>
            </div>

This is the function of ajax within the same HTML

<script>        
       $(document).ready(function () {

          $("#boton2").click(function () {
          var DATE = $("#DATE").val();
          var NAME = $("#NAME").val();
          var DESCR = $("#DESCR").val();
          var IMG = $("#IMG").val();
          var COSTO = $("#COSTO").val();


          $.post("saveFitGreenMenu.php", {
            DATE: DATE,
            NAME: NAME,
            DESCR: DESCR,
            IMG: IMG,
            COSTO: COSTO
          },
          function (data, status) {
               console.log(data);
          });
        }); 
       });

    </script>

This is all I have in the php to save

<?php
include "conexionFitGreen.php";

if(mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }else{

$DATE = $_POST["DATE"];
$NAME = $_POST["NAME"];
$DESCR = $_POST["DESCR"];
$IMG = $_FILES["IMG"];
$COSTO = $_POST["COSTO"];


    if($con){
      //Paso 2
      $sentencia = $con->prepare("
        insert into menudia(DATE, NAME, DESCR, IMG, COSTO) 
        values(?, ?, ?, ?, ?)");
      //Paso 3
      $sentencia->bind_param("sssbi", $DATE, $NAME, $DESCR, $IMG, $COSTO);


      //Paso 4
      if($sentencia->execute()){
        //echo "Datos del paciente guardados exitosamente!";
      }

      $sentencia = $con->prepare("select * from menudia");
      if($sentencia->execute()){
        $sentencia->bind_result($DATE, $NAME, $DESCR, $IMG, $COSTO, $ID);

      }
  }
}

?>

I hope you can help me. I know that everything is fine since the other parameters keep them without problems, but the image always goes blank in the database. Thank you very much in advance.

    
asked by Carolina Franco 30.11.2017 в 14:43
source

2 answers

1

try the following:

The code has the comments for you to see the process

$(document).ready(function() {

  $("#boton2").click(function() {
    //obtine el archivo para enviar por POST:
    var IMG = document.getElementById("IMG");
    var file = IMG.files[0];

    //crea el JSON con los datos
    var datos = {
      DATE: $("#DATE").val(),
      NAME: $("#NAME").val(),
      DESCR: $("#DESCR").val(),
      COSTO: $("#COSTO").val()
    };

    //DATA sera la variable que guarde lo que envia
    //por POST con formatData()
    var data = new FormData();
    data.append('img', file); //agrega el archivo(imagen)
    data.append('datos', JSON.stringify(datos)); //agrega el json con los demas datos

    //Usa $AJAX en lugar de $POST
    $.ajax({
      type: "post", //tipo de envio
      contentType: false,
      data: data, //la información que envia
      processData: false,
      async: false, //espera respuesta del servidor antes de continuar
      url: 'saveFitGreenMenu.php', //url del PHP
      success: function(response) { //si la petición fue exitosa
        alert('Registro Completo');
      }
    });
  });
});
<?php
include "conexionFitGreen.php";

if(mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }else{
    //obtiene los datos por POST
    $DATOS = json_decode($_POST['datos'],true);
    //separa los datos
    $DATE = $DATOS["DATE"];
    $NAME = $DATOS["NAME"];
    $DESCR = $DATOS["DESCR"];
    $COSTO = $DATOS["COSTO"];
    
    //obtiene el archivo por FILE
    $IMG = $_FILES['img']['tmp_name']; //así obtiene el archivo FILE
    $IMGNAME = $_FILES['img']['name'];     //así obtiene el nombre del archivo FILE
    $RUTA = 'mifolder/imagenes';       //aqui especifica la ruta en donde cargar la imagen

    //ASI SUBE EL ARCHIVO AL SERVIDOR
	  if (!move_uploaded_file($IMG, $RUTA)) {
		  $return = false;
	  }

    if($con){
      //Paso 2
      $sentencia = $con->prepare("
        insert into menudia(DATE, NAME, DESCR, IMG, COSTO) 
        values(?, ?, ?, ?, ?)");
      //Paso 3
      //$IMGNAME para guardar el nombre de la imagen nada más
      $sentencia->bind_param("sssbi", $DATE, $NAME, $DESCR, $IMGNAME, $COSTO);


      //Paso 4
      if($sentencia->execute()){
        //echo "Datos del paciente guardados exitosamente!";
      }

      $sentencia = $con->prepare("select * from menudia");
      if($sentencia->execute()){
        $sentencia->bind_result($DATE, $NAME, $DESCR, $IMGNAME, $COSTO, $ID);

      }
  }
}

?>
    
answered by 30.11.2017 в 15:12
-1

It is not recommended or normalized to save the files (images, pdf, ...) as binary in the BDD.

Change your save method by copying the image to a directory accessible by the web application and saving the path to that copy in the database.

I'm sorry, my knowledge of PHP is basic and that's why I do not put you on it, but I think it's important to let you know this good practice.

    
answered by 30.11.2017 в 14:50