Gelera I'm beating myself a little bit to find out what's happening with a code I've assembled.
I have a loop that downloads .csv
files from a specific server to my server. There are 9 files.
After completing the downloads I need to delete the bases, perform the insertions again and delete the files, it seemed simple but some things are getting out of control.
In the beginning the file "insert_delete.php" received the 3 loops of the 9 files, however it was lost and registered logs informing duplicate of insertions and delete of files. So I separated into 3 files, that stopped happening.
A strange question is that when I execute directly the file "insert_delete.php" everything happens inside the conforming ones, however when executed by script
the base is going blank, as if TRUNCATE
happened after foreach
.
It seems like something is happening and I can not see.
Let's go to the mess I made:
Script
//Contagem dos arquivos se houver mais que 8 arquivos realiza a solicitação de inserção, se não continua contando
function cont(){
setTimeout(function(){
$.get("query/cont_arquivos.php", function( data ) {
if(data < 9){
$('.box_loading').show();
$(".cont").html(
"Aguardando arquivos "+data
);
cont();
}else{
$.get("insert_delete.php", function(){});
$.get("insert_delete1.php", function(){
$('.box_loading').hide();
});
$.get("insert_delete2.php", function(){});
$(".cont").html(
"Inserindo nas bases... "
);
}
});
},1000);
}
PHP (insert delete)
<?php
include "conn.php";
$files1 = glob('nomedosarquivos*.csv'); // obten alguns arquivos da pasta
$sql = "TRUNCATE TABLE nomedatabela"; //apaga a base
$conn->query($sql);
if(count($files1)>2){
foreach($files1 as $file){ // loop dos 3 arquivos
if(is_file($file))
if (($base = fopen($file, "r")) !== FALSE) {
$count = 0;
$ok = 0;
$erro = 0;
while (($data = fgetcsv($base, 0, ";")) !== FALSE) {
$data = array_map("utf8_encode", $data);
$count++; //contar as linhas
if ($count == 1) { continue; } //não inserir os titulos
if ($data[0] == "") { break; } //sai do while se este campo estiver em branco
//validações de campos
$sql = "INSERT into nomedatabela (campos....) VALUES (dados..)";
if($conn->query($sql)==TRUE){
$ok++;
//somente conta as linhas que foram inseridas
}else{
//conta os erros
$erro++;
//executa o log informando qual erro e em qual linha aconteceu
}
}
fclose ($base);
if(unlink($file)){
//executa o log informando que o arquivo foi deletado
}else{
//executa o log informando um erro ao deletar o arquivo
}
}
}
}
?>