Upload multiple images with id from another table? [closed]

0

I am trying to upload multiple images when creating a new product and save those images in a table called galeria next to id of the product created.

The error I have is that the id and the date are saved in the galeria table but the name of the letter image is id / row and the producto_id is null.

If they know a way to do it better, they tell me about it

My tables are:

products
- product_id
- producto_title
- product_price
- producto_description
- producto_image


gallery
- imagen_id
- imagen_name
- imagen_date
- product_id

code

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $producto_steps = $_POST['producto_title'];
    $producto_price = $_POST['producto_price'];
    $producto_description = $_POST['producto_description'];

    $producto_image = $_FILES['producto_image']['tmp_name'];

    $producto_image_upload = '../' . $items_config['images_folder'] . $_FILES['producto_image']['name'];

    move_uploaded_file($producto_image, $producto_image_upload);

    $statment = $connect->prepare(
        'INSERT INTO productos (producto_id,producto_title,producto_price,producto_description,producto_image) VALUES (null, :producto_title, :producto_price, :producto_description, :producto_image)'
        );

   $statment->execute(array(
        ':producto_title' => $producto_title,
        ':producto_price' => $producto_price,
        ':producto_description' => $producto_description,
        ':producto_image' => $_FILES['producto_image']['name']
        ));

// SUBIR IMAGENES

$i=0;

  foreach ($_FILES['imagen_name']['name'] as $f)
  {
     $imagen_name = $_FILES['imagen_name']['tmp_name'][$i];
     $imagen_name_upload = '../' . $items_config['imagenes_folder'] . $_FILES['imagen_name']['name'];
     move_uploaded_file($imagen_name, $imagen_name_upload);

     $statment = $connect->prepare(
    'INSERT INTO galeria (imagen_id, producto_id,imagen_name,imagen_date) VALUES (null,:prod_id,:imagen_name,CURRENT_TIMESTAMP)'
     );

     $statment->execute(array(
         ':prod_id' => $producto_id,
         ':imagen_name' => $_FILES['imagen_name']['name'][$i]
     ));

     $i++;

   }

    
asked by anonfidusa 28.04.2017 в 10:19
source

1 answer

2

You can use lastInsertId () to retrieve the id of the last record inserted.

// DESPUES DE HACER LA INSERCION RECUPERAS EL ID DEL PRODUCTO
$producto_id = $connect->lastInsertId();

An example to upload multiple images could be something like this, it is imperative that in the image field of the form, the name, be an array ( name="myName []" ):

<?php
/**
* 
* @author XERIFANDTOMAS
*
* Subida de multiples imagens
*
* @param array $file ( OBILIGATORIO )
*   Debe de pasarse $_FILES habiendo subido los archivos en el form con name="myNombre[]"
*
* @param string $nombre ( OPCIONAL )
*   Default: img
*   nombre para la imagen
*   Se añade marca de tiempo+identificador ( dmYHis-key )
*   Ejemplo: MyImg-21022016154613-1.jpg
*
* @param string $ruta ( OPCIONAL )
*   Default: $_SERVER['DOCUMENT_ROOT']/img/
*   Ruta de la imagen final, se debe proporcionar una ruta completa
*   Si la ruta no existe se intentara crear
*
* @param string $max_size ( OPCIONAL )
*   Default: 5000000 (5MB)
*   Tamaño máximo permitido de la imagen
*
* @param int $max_archivos ( OPCIONAL )
*   Default: 5
*   Número máximo de archivos que se pueden subir a la vez
*
*
* @return ARRAY / String
*  En caso de éxito:  Devuelve un array con los nombres de las imagenes
*  En caso de error:  Debuelve un string con el mensaje de error
*/
function upload_img($file,$nombre="img",$ruta="",$max_size= "5000000",$max_archivos=5)
{
    $tipos_de_archivos= array("image/jpeg","image/jpg", "image/png");

    if ($ruta=="") {
        $ruta = $_SERVER['DOCUMENT_ROOT']."/img/";
    }
    if ( !file_exists($ruta) ) { 
        if( !mkdir($ruta, 0775, true) ){
            return 'el directorio no existe y no se puedo crear.';
        }
    }

    $key_files=array_keys($file);
    $numero_de_archivos= count($file[$key_files[0]]['name']);

    if ($numero_de_archivos<1) {
        return 'No se ha cargado ning&uacute;n archivo.';
    }
    if ($numero_de_archivos>$max_archivos) {
        return 'Solo se pueden subir <b>'.$max_archivos.' archivos</b> a la vez.';
    }
    if ( !is_array($file[$key_files[0]]['tmp_name']) ){
        return 'Se deben subir los archivos como un array.';
    }

    $tmp_name= $file[$key_files[0]]['tmp_name'];
    $type= $file[$key_files[0]]['type'];
    $size= $file[$key_files[0]]['size'];
    $name= $file[$key_files[0]]['name'];
    $error= $file[$key_files[0]]['error'];

    foreach ($tmp_name as $k => $v) {
        if (!is_uploaded_file($v)) {
            return '<br/>El archivo <b>'.$name[$k].'</b> ha dado error.';
        }
    }
    foreach ($error as $k => $v) {
        if ($v!==0) {
            return '<br/>El archivo <b>'.$name[$k].'</b> ha dado error al cargar.';
        }
    }
    foreach ($type as $k => $v) {
        if (!in_array($v, $tipos_de_archivos)){
            return '<br/>El archivo <b>'.$name[$k].'</b> no esta permitido. Solo archivos JPG, JPEG, PNG.';
        }
    }
    foreach ($size as $k => $v) {
        if ($v>$max_size) {
            return '<br/>El archivo <b>'.$name[$k].'</b> supera el tama&ntilde;o permitido.';
        }
    }
    foreach ($name as $k => $v) {
        $extension = end(explode('.', $v));
        $nombre_final[$k]=$nombre.'-'.date('dmYHis').'-'.$k.'.'.$extension; 
    }
    foreach ($tmp_name as $k => $v) {
        $destino= $ruta.$nombre_final[$k];
        if(!move_uploaded_file($v, $destino)){
            return 'No se ha podido mover el archivo al servidor.';
        }
        $n[]=$nombre_final[$k];
    }
return $n;
}

Your code would look something like this:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

$categoria_lists = $_POST['categoria_id'];
$product_name = cleardata($_POST['product_name']);
$nombreImg = removeSymbols($product_name);

$pathImg = '../' . $items_config['images_folder'];

$archivos = upload_img($_FILES, $nombreImg.'-principal', 0, $pathImg);

$statment = $connect->prepare(
    'INSERT INTO products (product_name,product_image) VALUES (:product_name, :product_image)'
    );

$statment->execute(array(
    ':product_name' => $product_name,
    ':product_image' => $_FILES['product_image']['name']
    ));

// recuperamos el id
$producto_id = $connect->lastInsertId();
unset($temp);

//comprobamos si existen categorias
if (count($categoria_lists)>0){
    $statment = $connect->prepare( 'INSERT INTO products_categorias (categoria_id,product_id) VALUES (:categoria_id, :product_id)' );
    $statment->bindParam(':categoria_id', $idcategoria);
    $statment->bindParam(':product_id', $producto_id);

        foreach ($categoria_lists as $option_value)
        {
           $idcategoria = $option_value;
           $statment->execute();
        }
}

$statment->bindParam(':product_id', $producto_id);

// SUBIR imageES
$nombreImg = removeSymbols($product_name);
$archivos = upload_img($_FILES, $nombreImg, 1, $pathImg);
// comprobamos que nos devuelve un array
if ( !is_array($archivos) ) {
    // error
    echo $archivos;
    return;
}

// Guardamos las imagees en la base de datos
$statment = $connect->prepare(
    'INSERT INTO galeria (product_id,image_name,image_date) VALUES (:product_id,:image_name,CURRENT_TIMESTAMP)'
);

foreach ($archivos as $key => $nombre)
{
    $statment->execute(array(
         ':product_id' => $producto_id,
         ':image_name' => $nombre
    ));
}


}
    
answered by 28.04.2017 / 10:38
source