PHP - Upload Multiple images

Asked

Viewed 195 times

-4

Hello,

I created a code where I simply upload multiple images.

But I’m not able to enter the values of the urls 'im/pd/'. $file_name_new; of the variable $file_destination in the comic book.

At DB I have..

User_id | img1 | img2 |

What should I include in the code so that urls are 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 $praBanco

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

  $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 or show errors...

I think it’s about this: $columns = '$praBanco'

The goal is that it add in the Database the path of the amount of images uploaded. As was done in INSERT, now click UPLOAD.

1 answer

3


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

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

I am doing example with the PHP extension mysqli but you use your.

 <?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 be 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 it would only save in the bank in MAXIMO until the amount of existing columns


As requested in the AP comment mas como faço agora para ele MOVER as 2 IMAGENS para a Folder? I edited the question and the answer to cover that situation.

To save images to folder

just insert into the code move_uploaded_file($file_tmp, $file_destination);

Situations to consider

1 - All images sent by form

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

2 - Only those whose urls were saved in the database

Insert the line inside the conditional

................
................
if ($j<$colBanco){
    $praBanco .="'".$file_destination."',";
    move_uploaded_file($file_tmp, $file_destination)
}
$j++;
...............
...............
  • Liked, very good, but as I do now for it MOVE the 2 IMAGES to the Folder?

  • Could you help me @Leo Caracciolo

  • Hey Friend... eheheh i’ve got one mroe Question to Ask u... i Did a update query.... but is not updating... can you Please check my code...

  • $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'";&#xA; $smtp_request_query = $con->query($smtp_process);

  • @user21312321, Ask a new Question and Tell me here what the link in the post is. To show you how to do through comment gets difficult. Ask a new question and tell me here which link of the post.

  • Sorry. I didn’t answer. That’s right, I have a part of the code that is exactly the same as that of sending multiple images, instead of being in INSERT will be in an UPDATE...

  • @user21312321, then ask a new question by posting the code you put in the comment above that I give you a solution because here with comment it is difficult and unintelligible the answer. As soon as you post the question leave a comment here

  • Leo Caracciolo, I sent the bug up New Error, help sff.

  • @user21312321 , ask new question for this post do not get confused! Puts what you had done as an answer that I edit to be in agreement

  • Simply, as you did before... Add the Images in INSERT... press UPLOAD.. is just set the variables inside the UPLOAD.... Can help?

  • Yes, but ask a new question, it costs nothing to do right!!!!!!

  • Of course, this one https://answall.com/questions/291503/php-upload-errors

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.