Importing .txt using php + mysql

0

Good evening, I've tried other ways but I could not. I need to run the query from the code below in one go instead of inserting row by row in the database. Would anyone have salvation?

<?php

set_time_limit(0);
if (!isset($seguranca)) {
exit;
}
$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

//ler todo o arquivo para um array
$dados = file($arquivo_tmp);

//Ler os dados do array
foreach ($dados as $linha) {
//Retirar os espaços em branco no inicio e no final da string
$linha = trim($linha);
//Colocar em um array cada item separado pela virgula na string
$valor = explode(',', $linha);

//Recuperar o valor do array indicando qual posição do array requerido e atribuindo para um variável
$data = $valor[0];
$hora = $valor[1];
$pis = $valor[2];



//Criar a QUERY com PHP para inserir os dados no banco de dados
$result_usuario = "INSERT INTO func_batidas (data, hora, pis) VALUES ('$data', '$hora', '$pis')";
//Executar a QUERY para inserir os registros no banco de dados com MySQLi
$resultado_usuario = mysqli_query($conectar, $result_usuario);
}
//Criar a variável global com a mensagem de sucesso
//Redirecionar o usuário com PHP para a página index.php
$_SESSION['msg'] = "<div class='alert alert-success'>Batidas importadas!</div>";
$url_destino = pg . "/listar/list_importa_batidas";
header("Location: $url_destino");
    
asked by anonymous 03.03.2018 / 22:57

1 answer

0

You can use transaction . If you do not know what this is, I recommend reading the question below.

In the% wrapper extension, we can start a transaction using the mysqli_* method or the begin_transaction function, for example:

/**
 * Orientado à Objeto
 * Inicia a transação apenas para leitura
 */
$conn->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);

/**
 * Procedural
 * Inicia a transação para leitura e escrita
 */
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_WRITE);

After starting the transaction, we can inform our queries using the function mysqli_begin_transaction or mysqli_query , for example:

/**
 * Orientado à Objeto
 */
$conn->query("INSERT INTO ...");

/**
 * Procedural
 */
mysqli_query($conn, "INSERT INTO...");

We can "commit" our transaction. This means that everything we do after query will be executed in the database.

An alternative is the begin_transaction function or the mysqli_multi_query method. As the name itself says, here we can enter several queries delimited by a character (usually the character is multi_query );

To do this, just save the queries in an array , for example:

$queries = [];

foreach ($dados as $linha) {
    $queries[] = "INSERT INTO func_batidas (data, hora, pis) VALUES ('$data', '$hora', '$pis')";
}
  

Please note that we do not add a delimiter at the end, we'll do it in the next step.

Now we just need to transform this array into string and also add our delimiter, so we can use the ponto-e-vírgula function,

/**
 * Orientado à Objeto
 */
$conn->multi_query( implode(";", $queries) );

/**
 * Procedural
 */
mysqli_multi_query($link, implode(";", $queries) );
Ready! In this way the implode extension will be in charge of executing all queries at the same time.

    
03.03.2018 / 23:47