save photos and data with php and mysql

0

Hello, I am making some adjustments to an inventory control website and they ask me to create an option to put photos to the products and that when editing the product data it is possible to edit the photo among other things, but in this it's what I've stuck in. Now in the code you see the image that I assign to the product from the database

<img src="<?php echo $row['foto' ]?>">

This works well, the problem is that when you complete the form, you do not save the image in the folder that you assigned, all other data such as name, id, etc. are saved without problems

and gives me these errorer:

Notice: Undefined index: mod_foto in C:\xampp\htdocs\ajax\editar_producto.php on line 63

Notice: Undefined index: mod_foto in C:\xampp\htdocs\ajax\editar_producto.php on line 64

Notice: Undefined index: mod_foto in C:\xampp\htdocs\ajax\editar_producto.php on line 65

Notice: Undefined index: mod_foto in C:\xampp\htdocs\ajax\editar_producto.php on line 66

Files

<?php
    include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/*Inicia validacion del lado del servidor*/
    if (empty($_POST['mod_id'])) {
           $errors[] = "ID vacío";
        }else if (empty($_POST['mod_codigo'])) {
           $errors[] = "Código vacío";
        } else if (empty($_POST['mod_nombre'])){
            $errors[] = "Nombre del producto vacío";
        } else if ($_POST['mod_categoria']==""){
            $errors[] = "Selecciona la categoría del producto";
        } else if (empty($_POST['mod_precio'])){
            $errors[] = "Precio de venta vacío";
        } else if (
            !empty($_POST['mod_id']) &&
            !empty($_POST['mod_codigo']) &&
            !empty($_POST['mod_nombre']) &&
            $_POST['mod_categoria']!="" &&
            !empty($_POST['mod_precio'])
        ){
        /* Connect To Database*/
        require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
        require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
        // escaping, additionally removing everything that could be (html/javascript-) code
        /*$tamanioPermitido = 200 * 1024;

//Tenemos una lista con las extensiones que aceptaremos
$extensionesPermitidas = array("jpg", "jpeg", "gif", "png");

//Obtenemos la extensión del archivo
$extension = explode(".", $_FILES["mod_foto"]["name"]);

//Validamos el tipo de archivo, el tamaño en bytes y que la extensión sea válida
if ((($_FILES["mod_foto"]["type"] == "image/gif")
      || ($_FILES["mod_foto"]["type"] == "image/jpeg")
      || ($_FILES["mod_foto"]["type"] == "image/png")
      || ($_FILES["mod_foto"]["type"] == "image/pjpeg"))
      && ($_FILES["mod_foto"]["size"] < $tamanioPermitido)
      && in_array($extension, $extensionesPermitidas)){
              //Si no hubo un error al subir el archivo temporalmente
              if ($_FILES["mod_foto"]["error"] > 0){
                     echo "Return Code: " . $_FILES["mod_foto"]["error"] . "<br />";
              }
              else{
                    //Si el archivo ya existe se muestra el mensaje de error
                    if (file_exists("../img/productos/" . $_FILES["mod_foto"]["name"])){
                           echo $_FILES["mod_foto"]["name"] . " already exists. ";
                    }
                    else{
                           //Se mueve el archivo de su ruta temporal a una ruta establecida
                           move_uploaded_file($_FILES["mod_foto"]["tmp_name"],
                                   "../img/productos/" . $_FILES["mod_foto"]["name"]);

                    }
              }
}
else{
     echo "Archivo inválido";
}
    */
    $variable = isset($_POST['mod_foto'])? $_POST['mod_foto']:'';
    print_r($variable);
    if ((($_FILES["mod_foto"]["type"] == "image/gif")
      || ($_FILES["mod_foto"]["type"] == "image/jpeg")
      || ($_FILES["mod_foto"]["type"] == "image/png")
      || ($_FILES["mod_foto"]["type"] == "image/pjpeg"))
      && ($_FILES["mod_foto"]["size"] < $tamanioPermitido)
      && in_array($extension, $extensionesPermitidas)){
              //Si no hubo un error al subir el archivo temporalmente
              if ($_FILES["mod_foto"]["error"] > 0){
                     echo "Return Code: " . $_FILES["mod_foto"]["error"] . "<br />";
              }
              else{
                    //Si el archivo ya existe se muestra el mensaje de error
                    if (file_exists("../img/productos/" . $_FILES["mod_foto"]["name"])){
                           echo $_FILES["mod_foto"]["name"] . " already exists. ";
                    }
                    else{
                           //Se mueve el archivo de su ruta temporal a una ruta establecida
                           move_uploaded_file($_FILES["mod_foto"]["tmp_name"],
                                   "../img/productos/" . $_FILES["mod_foto"]["name"]);
                                    }
              }
}

    $ruta='img/productos/';

        $codigo=mysqli_real_escape_string($con,(strip_tags($_POST["mod_codigo"],ENT_QUOTES)));
        $nombre=mysqli_real_escape_string($con,(strip_tags($_POST["mod_nombre"],ENT_QUOTES)));
        $descripcion=mysqli_real_escape_string($con,(strip_tags($_POST["mod_descripcion"],ENT_QUOTES)));
        $categoria=intval($_POST['mod_categoria']);
        $stock=intval($_POST['mod_stock']);
        $precio_venta=floatval($_POST['mod_precio']);
        $id_producto=$_POST['mod_id'];
        $sql="UPDATE products SET codigo_producto='".$codigo."', nombre_producto='".$nombre."', id_categoria='".$categoria."', precio_producto='".$precio_venta."', stock='".$stock."', descripcion='".$descripcion."', foto='".$ruta."' WHERE id_producto='".$id_producto."'";
        $query_update = mysqli_query($con,$sql);
            if ($query_update){
                $messages[] = "Producto ha sido actualizado satisfactoriamente.";
            } else{
                $errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con);
            }
        } else {
            $errors []= "Error desconocido.";
        }

        if (isset($errors)){

            ?>
            <div class="alert alert-danger" role="alert">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>Error!</strong> 
                    <?php
                        foreach ($errors as $error) {
                                echo $error;
                            }
                        ?>
            </div>
            <?php
            }
            if (isset($messages)){

                ?>
                <div class="alert alert-success" role="alert">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong>¡Bien hecho!</strong>
                        <?php
                            foreach ($messages as $message) {
                                    echo $message;
                                }
                            ?>
                </div>
                <?php
            }

?>

this is the html of the form

<?php
    if (isset($con))
    {
?>
<!-- Modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel"><i class='glyphicon glyphicon-edit'></i> Editar producto</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" method="post" id="editar_producto" name="editar_producto" action="editar_producto.php"  enctype="multipart/form-data">
        <div id="resultados_ajax2"></div>
          <div class="form-group">
            <label for="mod_codigo" class="col-sm-3 control-label">Código</label>
            <div class="col-sm-8">
              <input type="text" class="form-control" id="mod_codigo" name="mod_codigo" placeholder="Código del producto" required>
                <input type="hidden" name="mod_id" id="mod_id">
            </div>
          </div>
           <div class="form-group">
            <label for="mod_nombre" class="col-sm-3 control-label">Nombre</label>
            <div class="col-sm-8">
              <textarea class="form-control" id="mod_nombre" name="mod_nombre" placeholder="Nombre del producto" required></textarea>
            </div>
          </div>

          <div class="form-group">
            <label for="mod_categoria" class="col-sm-3 control-label">Categoría</label>
            <div class="col-sm-8">
                <select class='form-control' name='mod_categoria' id='mod_categoria' required>
                    <option value="">Selecciona una categoría</option>
                        <?php 
                        $query_categoria=mysqli_query($con,"select * from categorias order by nombre_categoria");
                        while($rw=mysqli_fetch_array($query_categoria)) {
                            ?>
                        <option value="<?php echo $rw['id_categoria'];?>"><?php echo $rw['nombre_categoria'];?></option>            
                            <?php
                        }
                        ?>
                </select>             
            </div>
          </div>

          <div class="form-group">
            <label for="mod_precio" class="col-sm-3 control-label">Precio</label>
            <div class="col-sm-8">
              <input type="text" class="form-control" id="mod_precio" name="mod_precio" placeholder="Precio de venta del producto" required pattern="^[0-9]{1,5}(\.[0-9]{0,2})?$" title="Ingresa sólo números con 0 ó 2 decimales" maxlength="8">
            </div>
          </div>

         <div class="form-group">
            <label for="mod_stock" class="col-sm-3 control-label">Stock</label>
            <div class="col-sm-8">
              <input type="number" min="0" class="form-control" id="mod_stock" name="mod_stock" placeholder="Inventario inicial" required  maxlength="8" readonly>
            </div>
        </div>
        <div class="form-group">
            <label for="mod_descripcion" class="col-sm-3 control-label">Descripci&oacute;n del Producto</label>
            <div class="col-sm-8">
              <textarea class="form-control" id="mod_descripcion" name="mod_descripcion" placeholder="Descripci&oacute;n del producto" ></textarea>
            </div>
        </div>
    <div class="form-group">
        <p>
          <label for="mod_foto" class="col-sm-3 control-label">Insertar Foto del Producto</label>
          <div class="col-sm-8">


          <input id="mod_foto" type="file" name="mod_foto" />

      </div>
          </div>


      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
        <button type="submit" class="btn btn-primary" id="actualizar_datos">Actualizar datos</button>
      </div>
      </form>
    </div>
  </div>
</div>
<?php
    }
?>

Thanks and regards

    
asked by Mauro Cortina Reyes 07.12.2018 в 22:35
source

1 answer

0

There are several errors in your code

1.- The error you indicate says that your "mod_foto" field is not reaching your backend. First you have to validate that you are sending the request $ _FILES

if ($_FILES){

that will stop you from giving that error, but now you have to check why it does not arrive, the most likely thing is that your form does not have the correct enctype

should look like this:

<form method="POST" enctype="multipart/form-data">

If you do not place the multipart / form-data, even if you have an input file, it will not be sent.

then in your validator in the part of allowed extensions you do an explode to obtain the extension of the file but you pass an array to it

in_array($extension, $extensionesPermitidas)) //esto es incorrecto

in_array($extension[1], $extensionesPermitidas)) // esto es lo correcto 

the 1 is because when you exploit the names you get this ['file name', '.jpg'] where $ extension [0] = > 'file name' and $ extension [1] = > '.jpg' thus already validates correctly. Finally, if you have problems with the move upload, you can add a DIR to move to the route you want. That's how the code was with all the changes I made and it works for me. I hope it will be helpful.

<!-- Formulario html (Omití los otros campos por comodidad) -->
<form method="POST" enctype="multipart/form-data">
<label for="mod_foto" class="col-sm-3 control-label">Insertar Foto del Producto</label>
<input id="mod_foto" type="file" name="mod_foto" />

<input type="submit" name="">

$tamanioPermitido = 200 * 1024;
//Tenemos una lista con las extensiones que aceptaremos
$extensionesPermitidas = array("jpg", "jpeg", "gif", "png");

//Validamos el tipo de archivo, el tamaño en bytes y que la extensión sea válida 
if ($_FILES){
    //Obtenemos la extensión del archivo
    $extension = explode(".", $_FILES["mod_foto"]["name"]);
    //Si no hubo un error al subir el archivo temporalmente 
    if ((
        ($_FILES["mod_foto"]["type"] == "image/gif")      ||
        ($_FILES["mod_foto"]["type"] == "image/jpeg")     ||
        ($_FILES["mod_foto"]["type"] == "image/png")      ||
        ($_FILES["mod_foto"]["type"] == "image/pjpeg"))   &&
        ($_FILES["mod_foto"]["size"] < $tamanioPermitido) &&
        in_array($extension[1], $extensionesPermitidas))
    {
        if ($_FILES["mod_foto"]["error"] > 0){
            echo "Return Code: " . $_FILES["mod_foto"]["error"] . "";
        } else { //Si el archivo ya existe se muestra el mensaje de error
            if (file_exists(__DIR__."/img/productos/" . $_FILES["mod_foto"]["name"])){
                echo $_FILES["mod_foto"]["name"] . " already exists. ";
            } else { //Se mueve el archivo de su ruta temporal a una ruta establecida
                move_uploaded_file($_FILES["mod_foto"]["tmp_name"], __DIR__."/img/productos/" . $_FILES["mod_foto"]["name"]);
            }
        }
    } else{
        echo "Archivo inválido";
    }
}
    
answered by 07.12.2018 в 23:50