PHP - Upload multiple images

-2

Hello,

I've created a code where I simply upload multiple images.

But I am not able to enter the values of the urls 'im/pd/'. $file_name_new; of the variable $file_destination in the DB.

In DB I have ..

User_id | img1 | img2 |

What should I include in the code so that urls is inserted in the Database and also how to save the images in the folder.

Code:

  //images function
           $ads_file = mysqli_real_escape_string($con, sanitize($_FILES['img_file']['name'][0]));  

           if(!empty($ads_file)) {

               $files = $_FILES['img_file'];
               $allowed = array('png', 'jpg', 'jpeg', 'gif');

               foreach($files['name'] as $position => $file_name) {

                   $file_tmp = $files['tmp_name'][$position];
                   $file_size = $files['size'][$position];
                   $file_error = $files['error'][$position];

                   $file_ext = explode('.', $file_name);
                   $file_ext = strtolower(end($file_ext));

                   if(in_array($file_ext, $allowed)) {

                        if($file_error === 0) {

                           if($file_size <= 4097152) {

                               $file_name_new = uniqid('', true) . '.' . $file_ext;
                               $file_destination = 'im/pd/'. $file_name_new;

                               $uploaded[$position] = $file_destination;
                               //define o caminho para o folder e para DB

                           } else {
                              $errors[] = "
                              <div class='alert warning'>
                                  <span class='closebtn'>&times;</span>  
                                  <strong><i class='fas fa-file-excel'></i></strong> Esta imagem é demasiado grande.
                              </div>";                               
                           }

                        } else {
                              $errors[] = "
                              <div class='alert warning'>
                                  <span class='closebtn'>&times;</span>  
                                  <strong><i class='fas fa-plug'></i></strong> Falha ao efetuar o upload. Tente novamente...
                              </div>";   
                        }

                   } else {
                         $errors[] = "
                         <div class='alert warning'>
                              <span class='closebtn'>&times;</span>  
                              <strong><i class='fas fa-file-excel'></i></strong> Ficheiro desconhecido, tente outro.
                         </div>";  
                   }
               }

          }  

New Error

I used the variables you gave me in relation to

 $praBanco .=" '".$file_destination."', ";

 for ($x = 1; $x <=$quantColunas; $x++) {
   $colunas.=" ads_image_".$x." = ";
}                   
$praBanco = substr($praBanco,0,-1); 
$colunas = substr($colunas,0,-1);

$ columns and $ bank

The problem is that ... It does not update because I think something is wrong regarding the entry in the update.

  $smtp_process = "UPDATE public_ads SET ads_title = '$ads_title', ads_content = '$ads_content', ads_price = '$ads_price', edit_attempts = edit_attempts + 1, $colunas = '$praBanco' WHERE ads_id = '$editor_id'"; 
  $smtp_request_query = $con->query($smtp_process);

But ... it does not update nor show errors ...

I think about this: $ columns = '$ bank'

The goal is for it to add in the Database the path of the number of uploaded images. As done in INSERT, now UPLOAD.

    
asked by anonymous 11.04.2018 / 17:42

1 answer

3
  

The solution is to create a variable $praBanco whose value will serve as VALUES in the declaration INSERT

$praBanco .="'".$file_destination."',";

I'm doing an example with the PHP extension mysqli but you use yours.

 <?php

....................
...................
if($file_size <= 4097152) {

    $file_name_new = uniqid('', true) . '.' . $file_ext;
    $file_destination = 'im/pd/'. $file_name_new;

    //vai servir pro VALUES do insert                       
    $praBanco .="'".$file_destination."',";
...................
...................


 if (isset($praBanco)){  

    $conn = new mysqli ("localhost", "USUARIO", "SENHA", "NOME_DB"); 

    //retira ultima virgula     
    $praBanco = substr($praBanco,0,-1);  

    /******* insert no banco ********/
    $sql = "INSERT INTO imagens(img1,img2) VALUES ($praBanco)";
    $qr=mysqli_query($conn,$sql); 
    mysqli_close($conn);

 }
?>

The optimal solution would look like this;

.....................................
.....................................

$files = $_FILES['img_file'];
$allowed = array('png', 'jpg', 'jpeg', 'gif');

 //numero de colunas no banco
 $colBanco=5;

 $j=0;

foreach($files['name'] as $position => $file_name) {

    $file_tmp = $files['tmp_name'][$position];
    $file_size = $files['size'][$position];
    $file_error = $files['error'][$position];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    if(in_array($file_ext, $allowed)) {

         if($file_error === 0) {

            if($file_size <= 4097152) {

                $file_name_new = uniqid('', true) . '.' . $file_ext;
                $file_destination = 'im/pd/'. $file_name_new;

                 //limita para a quantidade correspondente ao numero de colunas no banco
                 if ($j<$colBanco){
                    $praBanco .="'".$file_destination."',";
                 }
                 $j++;

                 $uploaded[$position] = $file_destination;
                 //define o caminho para o folder e para DB

.....................................
.....................................

     if (isset($praBanco)){
        /*****************************************************************************/
        //verificamos o numero de imagens para determinar o numero de colunas no banco.

        $quantColunas = substr_count($praBanco, ',');
        /*****************************************************************************/

        /****criamos os nomes das colunas para usar na declaração INSERT *******/
        for ($x = 1; $x <=$quantColunas; $x++) {
            $colunas.="img".$x.",";
        }
        /*****************************************************************************/


        /******* conexão ao banco - exemplo com a extensão do PHP mysqli ********/
        $conn = new mysqli ("localhost", "USUARIO", "SENHA", "NOME_DB");

        /**** retira a ultima virgula *******/     
        $praBanco = substr($praBanco,0,-1); 
        $colunas = substr($colunas,0,-1);
        /***********************************/

        /******* insert no banco ********/
        $sql = "INSERT INTO imagens ($colunas) VALUES ($praBanco)";
        echo $sql;
        $qr=mysqli_query($conn,$sql); 
        mysqli_close($conn);

   } 
  

In this case you would only save in the MAXIMO bank up to the amount of existing columns

As requested in the comments of% AP with% edited the question and answer to cover this situation.

To save the images in the

  

just insert in code mas como faço agora para ele MOVER as 2 IMAGENS para a Folder?

Situations to consider

1 - All images submitted by the form

................
................
if ($j<$colBanco){
    $praBanco .="'".$file_destination."',";
}
move_uploaded_file($file_tmp, $file_destination)
$j++;
...............
...............

2 - Only those whose urls have been saved in the database

Insert the line inside the conditional

................
................
if ($j<$colBanco){
    $praBanco .="'".$file_destination."',";
    move_uploaded_file($file_tmp, $file_destination)
}
$j++;
...............
...............
    
12.04.2018 / 20:50