Prevent duplication in the BD depending on the FOR loop

Asked

Viewed 49 times

0

I am creating a multiple image upload system. The "move_uploaded_file" function works fine. The problem is that I included a $grav insert for the BD, and as can be seen in the code, it would only be sent if the IF conditions of the images were respected. Only when the 'for' loop is running, it duplicates this insertion the number of times the indexed images are. If there are three, it will repeat the insertion three times, and so on, and I just wanted a single insertion. I saw in the Stack in English that there is the possibility of using ON DUPLICATE KEY UPDATE to avoid this duplication. But how would I do it?

//INFO IMAGEM
		$file 		= $_FILES['anexo'];
		$numFile	= count(array_filter($file['name']));
		
		//PASTA
		$folder		= 'docs';
		
		//REQUISITOS
		$permite 	= array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf');
		$maxSize	= 1024 * 1024 * 5;
		
		//MENSAGENS
		$msg		= array();
		$errorMsg	= array(
			1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
			2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
			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)) {

//abaixo a inserção que está sendo duplicada
					
                $grav = "INSERT INTO propostaveic (tipseguro, marca, modelo, anofabric, modeloano, cambauto, veicblind, veicualien, veicudefic, kitgas, taxi, naresidenc, notrab, nocolegio, ceppernoite, veicupresta, veic85pc, ponthabilit, cidade, data, cnh, usuario) 
                VALUES ('$seguro1', '$seguro2', '$seguro3', '$seguro4', '$seguro5', '$seguro6', '$seguro7', '$seguro8', '$seguro9', '$seguro10', '$seguro11', '$seguro12', '$seguro13', '$seguro14', '$seguro15', '$seguro16', '$seguro17', '$seguro18', '$seguro19', '$seguro20', '$seguro21', '$usuario')";
                $exe_grav = mysqli_query($bd, $grav);
             

			     $msg[] = "<b>$name :</b> Upload Realizado com Sucesso!"; 
					  
                 }

				 else {
				 $msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";}
				
				}
				
				foreach($msg as $pop)
					echo $pop.'<br>';
		    }
	  }

1 answer

1


You can only perform a count of uploaded images, and when you are done check if all images have been uploaded, using a counter, exemplifying:

Place a loaded image counter before the loop for

$imgscont = 0;

For each uploaded image you increment one

$imgscont++; // dentro do loop

After the loop for you insert into the BD

if($imgscont == $numFile){
    // Iserção no BD aqui assim como a mensagem
}
  • Leano, the problem of 'break' is that it will brake the loop after the first insertion, and the idea is not this, because I need it to move the files to the folder one by one after indexing.

  • I understand now your problem, I will post another answer with a new code

  • Excellent, Leano. It worked perfectly now. I’m sure it will be useful for many people. Thank you!

Browser other questions tagged

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