writing multiple images to the destination folder and to the database with php and mysql [closed]

3

How can I send 5 images to the destination folder (upload), and at the same time already save the names (img.jpeg) of these images in the database table, using PHP and MySql?

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 form, thus:

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 Upload file:

    <?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 this is what I have, if friends can help me to register the image files in the database and the destination folder simultaneously, I will be grateful. Hugs to all, and thanks for the attention.

    
asked by anonymous 04.11.2015 / 00:34

1 answer

0
The input responsible for selecting the image (s) usually has the multiple attribute 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 entries with the same name bracketed attribute so that the values are read as one (form an array) .

Usually when the variable _ $ FILES receives a set instead of a single file, the values are grouped in order by type instead of being 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 php you can iterate through 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 php script you would have something like this:

<?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 you can capture errors, MIME type and other details of the file (s) inside the loop, as in the example above.

For example, by adding the condition following the switch , we execute the passed statements 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 causes the sign.txt file to write all data relating to files with a MIME type 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>
Queries using UPDATE return Booleans for success, or failure.

Your question is about "How to write multiple files to the destination folder and the database" , while reading the explanatory part I found the same, but reading the script in>, it seems that there is more to be done with removing files from the destination folder, and from the database. However, UPDATE does not serve to remove, serves to update / modify table values, to remove data from the database is used DELETE .

  

If your question is about uploading multiple files to the destination folder and recording them at the same time in the database, then follow the steps I've described, otherwise edit the question and try to explain more about which is based on the problem.

    
04.11.2015 / 15:26