Multi upload with various php and mysql formats

Asked

Viewed 276 times

2

I would like to do a multi upload with various img formats, I am researching how it does using php 7.1, I understood more or less the logic of the business. I just can’t seem to reproduce.

Someone could give me a hand or link with a correct reference of the multi upload application with various file formats

== index.php
<body>
   <h3>Photo Gallery</h3>

   <form action="add-album.php" method="post">
   	    <label>Add New Album</label>
   	    <input type="text" name="album_name">
   	    <input type="submit" name="submit_album" value="Add">
</form>
<?php 

 if(isset($_GET['add_album_action'])){
 	if ($_GET['add_album_action'] == "sucessfull") { ?>
 	<br>New Album created <br><br>
 
 	<?php }
 }
 ?>
 <?php

$albums = $mysqli->query("SELECT * FROM gallery_albums");
while ($album_data = $albums->fetch_assoc()) {
	$photos = $mysqli->query("SELECT * FROM gallery_photos WHERE album_id = ".$album_data['album_id']."");?> 

<b>#<?php echo $album_data['album_id'] ?></b> <a href="view-album.php?album_id=<?php echo $album_data['album_id'] ?>"><?php echo $album_data['album_name'] ?></a> (<?php echo $photos->num_rows; ?>)<br><br>
<?php }
 ?>
</body>

upload_photo.php

<?php
include 'connection.php';



$album_id = $_GET['album_id'];
if ($_FILES['photo']['name'] != null) {


    move_uploaded_file($_FILES['photo']['tmp_name'], "images/". $_FILES['photo']['name']);

$photo_link = "images/". $_FILES['photo']['name'];
 
$upload_photo = $mysqli->query("INSERT INTO gallery_photos (album_id, photo_link) VALUES ($album_id, '$photo_link')");
if ($upload_photo) {


header("Location: view-album.php?album_id=$album_id&amp;upload_action=success");
} else {

echo $mysqli->error;
}

} else {
header("Location: index.php");
}
?>;
<?php
include 'connection.php';
if (isset($_GET['album_id'])) {
$album_id = $_GET['album_id'];
$get_album = $mysqli->query("SELECT * FROM gallery_albums WHERE album_id = $album_id");
$album_data = $get_album->fetch_assoc();
} else {
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $album_data['album_name'] ?></title>
</head>
<body>
<?php
$photo_count = $mysqli->query("SELECT * FROM gallery_photos WHERE album_id = $album_id");
?>
<a href="index.php">Home</a> | <?php echo $album_data['album_name'] ?> (<?php echo $photo_count->num_rows; ?>)<br><br>
<form method="post" action="upload_photo.php?album_id=<?php echo $album_id ?>" enctype="multipart/form-data">
<label>Add photo to this album:</label><br>
<input type="file" name="photo" /> 

<input type="submit" name="upload_photo" value="Upload" />
</form>
<?php
if (isset($_GET['upload_action'])) {
if ($_GET['upload_action'] == "success") { ?>
<br><br>Photo successfully added to this album<br><br>
<?php }
}
?>



<?php
$photos = $mysqli->query("SELECT * FROM gallery_photos WHERE album_id = $album_id");
while($photo_data = $photos->fetch_assoc()) { ?>
<img src="<?php echo $photo_data['photo_link'] ?>" width="200px" height="200px" />
<?php }
?>
</body>
</html>

  • First I suggest you learn to upload a simple file from a single file. A problem in what you posted starts from the basics in HTML. Tag <form> still missing the enctype="multipart/form-data" and an element input type="file". For now, what you ask is ample. There are many things since the upload and validation of file types. Ask only one thing.

  • I appreciate it! I will add and continue searching on.

1 answer

2


In one of my projects I had to carry out a treatment sementant to the proposed in the question. I’ve made a few adjustments to suit your scenario.

$files = $_FILES;
$config = [
    'type_file_allowed' => ['jpeg', 'png', 'jpg'],
    'file_error_message' => [
        0 => 'Não houve erro e o upload foi bem sucedido.',
        1 => 'O arquivo enviado excede o limite definido.',
        2 => 'O arquivo excede o limite definido em MAX_FILE_SIZE no formulário HTML.',
        3 => 'O upload do arquivo foi feito parcialmente.',
        4 => 'Nenhum arquivo foi anexado',
        6 => 'Pasta temporária estar ausente.',
        7 => 'Falha ao escrever o arquivo em disco.',
        8 => 'Uma extensão do PHP interrompeu o upload do arquivo.'
    ]
];

$upload_files = images($files, $config);
salve($upload_files);

function images($files, $config) {
    $images = [];
    $files = structureUploadFile($files);    

    foreach ($files as $key => $file) {    

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (!in_array($extension, $config['type_file_allowed'])) {
            throw new Exception('File extension '. $extension .' not allowed');
        }

        array_push($images,
            [
                'file' => [
                    'name' => strtolower($file['name']),
                    'path' => $file['tmp_name'],
                    'attach' => ($file['error'] == 4) ? false : true,
                    'file_message' => 
                       $config['file_error_message'][$file['error']]
                ]
            ]
        );
    }

    return $images;
}

function structureUploadFile($files) {
/*
Função responsável por transformar os atributos do file em chaves
Antes do método structureUploadFile o file vem agrupado assim:
array(1) {
  ["file"]=>
      array(5) {
        ["name"]=>
            array(2) {
              [0]=> string(13) "alert-git.png"
              [1]=> string(15) "arquivo git.png"
            }
        ["type"]=>
            array(2) {
              [0]=> string(9) "image/png"
              [1]=> string(9) "image/png"
            }
        ["tmp_name"]=>
            array(2) {
              [0]=> string(14) "/tmp/phpdDHYVq"
              [1]=> string(14) "/tmp/phpGVjQUt"
            }
        ["error"]=>
            array(2) {
              [0]=> int(0)
              [1]=> int(0)
            }
        ["size"]=>
            array(2) {
              [0]=> int(73549)
              [1]=> int(76928)
            }
      }
}

//Depois do método
array(2) {
  [0]=> array(5)
    {
        ["name"]=> string(13) "alert-git.png"
        ["type"]=> string(9) "image/png"
        ["tmp_name"]=> string(14) "/tmp/phpdDHYVq"
        ["error"]=> int(0)
        ["size"]=> int(73549)
    }
  [1]=> array(5)
    {
        ["name"]=> string(15) "arquivo git.png"
        ["type"]=> string(9) "image/png"
        ["tmp_name"]=> string(14) "/tmp/phpGVjQUt"
        ["error"]=> int(0)
        ["size"]=> int(76928)
     }
}

 */

    $file_identification = array_keys($files['file']['name']);

    $attribute = [];
    foreach ($files['file'] as $key_params => $params) {
        array_push($attribute, $key_params);
    }

    $data = [];
    foreach ($file_identification as $id) {
        $values = array_column($files['file'], $id);
        array_push($data, array_combine($attribute, $values));
    }

    return array_combine($file_identification, $data);
}

function salve($images) {
    foreach ($images['file'] as $key => $images) {
        if ($images['attach']) {
            //executa select
        }
    }
}

You haven’t said anything about how you’re getting the data, but if you need to work asynchronously, that is, without updating the page, you can use some javascript plugins, for example:

  • Djama and how would I process each array and place the multiples in the direct database? i might have to put a foreach and give an Insert I have the logica more the less

  • Yes. The code is just to assemble the structure to facilitate when saving. So you will have to make a foreach to walk the array, as per the function salve($images).

Browser other questions tagged

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