recording multiple images in the target folder and in the database with php and mysql

Asked

Viewed 1,625 times

3

You can send 5 images to the target folder (upload), and at the same time record the names (img.jpeg) of these images in the Database table, using PHP and Mysql?

Because I tried using the same reasoning as I use to send a single file, and I tried to adapt the upload files, upload_serv.php and the form, so this is how it is:

Form:

        <div align="center" style=" padding:2px; float:left; width:290px; height:auto;">
                <?php
                include '../conexao.php';

                $codigo = $_GET['codigo'];
                $query = mysql_query("SELECT * FROM serv WHERE codigo = '$codigo'");
                $res = mysql_fetch_array($query);

                $pasta = '../img_serv/';

                if (isset($_POST['upload'])){
                $check = @$_POST['apagar'];
                foreach($check as $img01){
                $delcheck = mysql_query("UPDATE serv SET img01='' WHERE codigo = '$codigo'") or die (mysql_error()); 
                unlink($pasta.'/'.$img01);

                foreach($check as $img02){
                $delcheck = mysql_query("UPDATE serv SET img02='' WHERE codigo = '$codigo'") or die (mysql_error()); 
                unlink($pasta.'/'.$img02);

                foreach($check as $img03){
                $delcheck = mysql_query("UPDATE serv SET img03='' WHERE codigo = '$codigo'") or die (mysql_error()); 
                unlink($pasta.'/'.$img03);

                foreach($check as $img04){
                $delcheck = mysql_query("UPDATE serv SET img04='' WHERE codigo = '$codigo'") or die (mysql_error()); 
                unlink($pasta.'/'.$img04);

                foreach($check as $img05){
                $delcheck = mysql_query("UPDATE serv SET img05='' WHERE codigo = '$codigo'") or die (mysql_error()); 
                unlink($pasta.'/'.$img05);

                if ($delcheck >= '1'){
                echo 'Imagem deletada com sucesso!';
                }else{
                echo 'Erro ao deletar imagem, tente novamente!';
                }}}}}}}
                ?>

                <?php include 'upload_serv.php'; ?>
   <form action="" method="post" enctype="multipart/form-data">
                <?php
                include '../conexao.php';
                $seleciona = "SELECT * FROM serv";
                $queryum = mysql_query($seleciona);
                while ($list = mysql_fetch_array($queryum)){
                $img01 = $_FILES['img01'];                  
                $img02 = $_FILES['img02'];
                $img03 = $_FILES['img03'];
                $img04 = $_FILES['img04'];
                $img05 = $_FILES['img05'];
                }
                ?>
                <input type="hidden" type="checkbox" name="apagar[]" value="<?php echo $img01;?>" checked readonly>
                <input type="hidden" type="checkbox" name="apagar[]" value="<?php echo $img02;?>" checked readonly>
                <input type="hidden" type="checkbox" name="apagar[]" value="<?php echo $img03;?>" checked readonly>
                <input type="hidden" type="checkbox" name="apagar[]" value="<?php echo $img04;?>" checked readonly>
                <input type="hidden" type="checkbox" name="apagar[]" value="<?php echo $img05;?>" checked readonly>

                <label>Selecione Imagem(ns)</label><br />
                <input type="file" name="img01[]" multiple="multiple" accept="image/*" ><br /><br />
                <input type="file" name="img02[]" multiple="multiple" accept="image/*" ><br /><br />
                <input type="file" name="img03[]" multiple="multiple" accept="image/*" ><br /><br />
                <input type="file" name="img04[]" multiple="multiple" accept="image/*" ><br /><br />
                <input type="file" name="img05[]" multiple="multiple" accept="image/*" ><br /><br />

    <input type="submit" name="upload" value="Upload">

    </form>
    </div>

The file Upload:

    <?php

    if(isset($_POST['enter'])){

    //INFO IMAGEM   
    $file = $_FILES['img01'];
    $numFile = count(array_filter($file['name']));

    $file = $_FILES['img02'];
    $numFile = count(array_filter($file['name']));

    $file = $_FILES['img03'];
    $numFile = count(array_filter($file['name']));

    $file = $_FILES['img04'];
    $numFile = count(array_filter($file['name']));

    $file = $_FILES['img05'];
    $numFile = count(array_filter($file['name']));

    //PASTA
    $folder = '../img_serv';

    //REQUiSITOS
    $permite = array('image/jpeg', 'image/png', 'image/gif');
    $maxSize = 1024 * 1024 * 5;

    //MENSAGEM
    $msg = array();
    $errorMsg = array(
    1 => 'O arquivo no upload é maior que o Limite de finido em upload_maxsize',
    2 => 'O arquivo ultrapassa o limite de tamanho em Max_file_size',
    3 => 'O upload do arquivo foi feito parcialmente',
    4 => 'Não foi feito o upload do arquivo', 
    );

    if($numFile <= 0)
    echo 'Selecione uma Imagem!!';
    else{
    for($i = 0; $i < $numFile; $i++){
    $name = $file['name'][$i];
    $type = $file['type'][$i];
    $size = $file['size'][$i];
    $error = $file['error'][$i];
    $tmp = $file['tmp_name'][$i];

    $extensao = @end(explode('.', $name));
    $novoNome = rand().".$extensao";

    if($error != 0)
    $msg[] = "<b>$name :</b> ".$errorMsg[$error];
    else if (!in_array($type, $permite))
    $msg[] = "<b>$name :</b> Erro imagem não suportada!";
    else if($size > $maxSize)
    $msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 5MB!";

    else{
    if(move_uploaded_file($tmp, $folder."/".$novoNome))             
    $img01 = $_FILES['img01'];
    $img02 = $_FILES['img02'];
    $img03 = $_FILES['img03'];
    $img04 = $_FILES['img04'];
    $img05 = $_FILES['img05'];

    $update = mysql_query("UPDATE serv SET img01 = '$novoNome', img02 = '$novoNome', img03 = '$novoNome', img04 = '$novoNome', img05 = '$novoNome' WHERE codigo = '$codigo'");

    if($update == ''){

    echo "<script language='javascript'>
           window.alert('Erro ao atualizar Imagem!!!');
           </script>";
    }else{
    echo "<meta http-equiv='refresh' content='0; URL= serv_edit.php'>
          <script language='javascript'>
          window.alert('Imagem atualizada com sucesso!');
          </script>";



    $msg[] = "<b>$name :</b> Upload realizado com sucesso!";
    else{
    $msg[] = "<b>$name :</b> Ocarreu um erro com o Upload!";

    }}}}}
    ?>

Well that’s what I have, if friends can help me to register the image files in the database and in the destination folder simultaneously, I’ll be grateful. Hugs to all, and thank you for your attention.

  • Take a look at this post, has to send 1 and multiple images as needed http://answall.com/questions/92974/upload-image/ does not have the sending snippet for the bd but is easy to implement.

1 answer

0

The input responsible for selecting the image(s), usually has the attribute Multiple in case you want the user to be able to select more than 1 file for that form, it is also possible to create 2 or more inputs with the same attribute name square brackets "[]" so that the values are read as one (form an array).

Usually when the variable _$FILES takes a set instead of a single file, values are grouped in order by type, instead of grouped by files.

Example:

//Ficheiro unico
<input type="file" name="imagem"/>

print_r($_FILES['imagem']);

Array (
       [name]=>exemplo.png [type]=>image/png [tmp_name]=> /tmp/phptemp [error]=>0 [size]=>420
       )

// Multiplos ficheiros
<input type="file" name="imagem[]" multiple/>

print_r($_FILES['imagem']);

Array (
       [name]=> Array([0]=>exemplo.png [1]=>exemplo1.png 
       [type]=> Array([0]=>image/png [1]=> image/jpeg
       [tmp_name]=> Array([0]=>/tmp/phptemp [1]=> /tmp/phptemp1
       [error]=> Array([0]=> 0 [1]=>0 
       [size]=> Array([0]=> 420 [1]=> 580
       )

With the php you can iterate this array to get each value and manipulate according to the type of work.

For a simple example, you would do the following for the html part:

<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="imagem[]" multiple/>
<input type="submit" name="enviar" value="ENVIAR"/>
</form>

And for the script php you’d have something like that:

<?php

if(isset($_POST['enviar']) && !empty($_POST['enviar'])){
    $imagem = isset($_FILES['imagem']) && !empty($_FILES['imagem']) ? $_FILES['imagem'] : NULL;
    // utilizando o $_FILES, a unica relacao existente
    // entre os ficheiros será o numero de indice, visto que  serão agrupados
    // por tipo consoante os indices de $_FILES
    if($imagem){
        $i=0;
        $plain = '';
        // iterando dessa forma, tem-se melhor controle da quantidade de elementos existente nessa array
        foreach($imagem['name'] as $img){
            switch($imagem['type'][$i]){
                case 'text/plain':
                // executar acçao caso formato corresponder
                $plain = 'sou texto simples';
                break;
                case 'image/png';
                // executar acçao caso formato corresponder
                $plain = 'sou imagem png';
                break;
                case 'image/jpg':
                // executar acçao caso formato corresponder
                $plain = 'sou imagem jpg';
                break;
                case 'image/jpeg':
                // executar acçao caso formato corresponder
                $plain = 'sou imagem jpeg';
                break;
                default:
            }
            echo $img . ' - ' . $imagem['size'][$i] . ' - ' . $imagem['type'][$i] . " <b>" . $plain . "</b><br/>";
            $i++;
        }
    } else {
        echo "Selecione um arquivo de imagem primeiro";
    }
}

?>

Using control structures one can capture errors, the mime type and other details of the file(s) inside the loop, as in the example above.

For example, adding the following condition to the switch, we execute the instructions given, only if the condition is true.

case 'image/png';
// executar acçao caso formato corresponder
// Exemplo
$plain = 'sou imagem PNG';
$dados = "Nome:" . $imagem['name'][$i] . "\n";
$dados .= "Nome temporario:" . $imagem['tmp_name'][$i] . "\n";
$dados .= "Tamanho:" . $imagem['size'][$i] . "\n";
$dados .= "Tipo MIME:" . $imagem['type'][$i] . "\n";
$fopen = fopen('assinar.txt','w');
fwrite($fopen, $dados);
fclose($fopen);
break;

This makes us write in the file sign.txt all data relating to MIME type files equal to image/png.

For an example using a database, it would be basically the same thing.

<?php

$con = new mysqli("localhost", "root", "", "tabela_mysql");
if($con->connect_errno){
    die('Conexao falhou: '. $con->connect_error);
}

if(isset($_POST['enviar']) && !empty($_POST['enviar'])){
    $imagem = isset($_FILES['imagem']) && !empty($_FILES['imagem']) ? $_FILES['imagem'] : NULL;
    if($imagem){
        $i=0;
        $plain = $msg = '';
        $upload = __DIR__.'/upload';
        foreach($imagem['name'] as $img){
            $query = "INSERT INTO imagens(nome) VALUES ('{$imagem['name'][$i]}')";
            if($con->query($query) && move_uploaded_file($imagem['tmp_name'][$i], $upload.'/'.$imagem['name'][$i])){
                $msg = "Ficheiros enviados e cadastrados";
            } 
            else {
                $msg = "Erro: falha ao inserir/cadastrar imagens \"" . $con->errno ? $con->error : '';
            }
            $i++;
        }
        echo isset($msg) ? $msg : '';
    } else {
        echo "Selecione um arquivo de imagem primeiro";
    }
}

?>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="imagem[]" multiple/>
<input type="submit" name="enviar" value="ENVIAR"/>
</form>

Consultations using UPDATE return boolean for success, or failure.

Your question is about "How to save multiple files to the destination folder and database", when reading the explanatory part I found the same, but when reading the script, seems to have more to do with removing files from the destination folder, and from the database. However, the UPDATE does not serve to remove, serves to update/modify table values, to remove database data is used DELETE.

If your question is about how to load multiple files to the target folder and how to save them at the same time to the database, then follow the steps I described, otherwise edit the question and try to explain more about what the problem is based on.

Browser other questions tagged

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