1
I’m making a form, where have a part of image registration for a photo gallery.
In this field I use a script with an add field button so that a new field can be inserted for each photo
<label>Galeria de Foto</label>
<BR><BR>
<button type="button" id="add_field" class="btn btn-success"><i class="fa fa-check"></i> Adicionar + Foto</button>
<br>
<div id="listas">
    <div><input name="fotos[]" type="file" class="form-control" aria-describedby="fileHelp" style="width: 70%;"></div>
</div>This is the script that adds the new field:
<script>
    $(document).ready(function() {
    var campos_max          = 10;   //max de 10 campos
    var x = 1; // campos iniciais
    $('#add_field').click (function(e) {
            e.preventDefault();     //prevenir novos clicks
            if (x < campos_max) {
                    $('#listas').append('<div>\
                    <input name="fotos[]" type="file" class="form-control" aria-describedby="fileHelp" style="width: 70%;">\
                            <a href="#" class="remover_campo">Remover</a>\
                            </div>');
                    x++;
            }
    });
    // Remover o div anterior
    $('#listas').on("click",".remover_campo",function(e) {
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
    });
});
</script>
So far so good. It creates a new file field, named pictures[]. And upload to the folder I set, without any error.
The problem is at the time of saving the name of each image in the database.
After submitting the form by post it executes the following:
<?
//include_once("config.php");
$nome_embarcacao = $_POST[nome];
$tipo = $_POST[tipo];
$arquivo = $_POST[arquivo];
$capacidade = $_POST[capacidade];
$tamanho = $_POST[tamanho];
$motorizacao = $_POST[motorizacao];
$equipamentos = $_POST[equipamentos];
$periodo_passeio = $_POST[periodo_passeio];
$area_navegacao = $_POST[area_navegacao];
$descricao = $_POST[descricao];
$sql = "INSERT INTO `embarcacao` (`id`, `nome`, `tipo`, `arquivo`, `capacidade`, `tamanho`, `motorizacao`, `equipamentos`, `periodo_passeio`, `area_navegacao`, `descricao`) VALUES (NULL, '$nome_embarcacao', '$tipo', '$arquivo', '$capacidade', '$tamanho', '$motorizacao', '$equipamentos', '$periodo_passeio', '$area_navegacao', '$descricao');";
$sql = mysql_query($sql);
$id_recuperado = mysql_insert_id();
// inicia criação de pasta
$pasta = @mkdir("../assets/images/embarcacoes/$id_recuperado");
// fim da criação da pasta
$uploaddir="../assets/images/embarcacoes/$id_recuperado/";
if($arquivo != "none") {// verifica campo foto 1
if (copy($_FILES['arquivo']['tmp_name'], $uploaddir . $_FILES['arquivo']['name'])) {
$varfoto01 = $_FILES['arquivo']['name'];
$var1 = mysql_query("update embarcacao set arquivo='$varfoto01' where 
id='$id_recuperado'");
}}
// Pasta de destino das fotos 
$Destino = "../assets/images/embarcacoes/$id_recuperado/"; 
// Obtém dados do upload 
$Fotos = $_FILES["fotos"]; 
// Contagem de fotos enviadas 
$Conta = 0; 
// Itera sobre as enviadas e processa as validações e upload 
for($i = 0; $i < sizeof($Fotos); $i++) 
{ 
 // Passa valores da iteração atual 
 $Nome = $Fotos["name"][$i]; 
 $Tamanho = $Fotos["size"][$i]; 
 $Tipo = $Fotos["type"][$i]; 
 $Tmpname = $Fotos["tmp_name"][$i]; 
 // Verifica se tem arquivo enviado 
if($Tamanho > 0 && strlen($Nome) > 1) 
{ 
 // Verifica se é uma imagem 
 if(preg_match("/^image\/(gif|jpeg|jpg|png)$/", $Tipo)) 
 { 
 // Caminho completo de destino da foto 
 $Caminho = $Destino . $Nome; 
 // Tudo OK! Move o upload! 
 if(move_uploaded_file($Tmpname, $Caminho)) 
 { 
 $sql_fotos = "INSERT INTO `embarcacao_fotos` (`id`, `id_embarcacao`, `arquivo`) VALUES";
foreach($_POST['fotos'] AS $indice => $valor) {
  $sql_fotos .= " (NULL, '{$id_recuperado}', '{$valor}'),";
}
echo "Foto #" . ($i+1) . " enviada.<br/>"; 
// Faz contagem de enviada com sucesso 
$Conta++; 
} 
else // Erro no envio 
{ 
 // $i+1 porque $i começa em zero 
 echo "Não foi possível enviar a foto #" . ($i+1) . "<br/>"; 
} 
} 
} 
} 
if($Conta) // Imagens foram enviadas, ok! 
{ 
echo "<br/>Foi(am) enviada(s) " . $Conta . " foto(s).";
} 
else // Nenhuma imagem enviada, faz alguma ação 
{ 
echo "Você não enviou fotos!"; 
}
?>
There in foreach($_POST['photos'], it does not insert in the database the name of each file.
I wonder if someone can help me. With this function of saving the names of the field files fotos[] in the database. That’s all I need. Save your names, because the upload in the created folder it is already doing normal.
I’m sorry if my post is duplicated and I’m sorry if I couldn’t explain it properly. I’m new at creating article to ask for help. I can always find someone with the same problem and solve by his question. But this one I’ve looked for and I haven’t found someone with the same problem.
Hug to all
You cannot terminate the SQL command with comma. And be careful that you are using the library
mysql_, which has been discontinued. See Why should we not use mysql type functions_*?– bfavaretto
Hello friend. Thank you for answering. Where is the comma you mentioned? Hug
– Agência Ozweb
Tell me what exactly you want to save in the bank with the variable
$valor– user60252
@Leocaracciolo then Leo, I want to save in the database the name of each file. The table has this structure that is there in Sql_photos. Uploading files is already normal. But the name does not save. It does not actually save any record.
– Agência Ozweb
If any answer solved your problem mark it as accepted. See how in https://i.stack.Imgur.com/evLUR.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
– user60252