txt file I inserted in the bd

0

Good, I'm making a website, where I will get a txt file that the user will upload (always in msm format (process, name, number)). I am trying to use arrays to fetch the data and insert it into the database. I already managed to fetch but I can not get the data in the array. for example, I have in the txt file this line (12345, andre, 1) and I want the array to be array 1 = 12345, array 2 = andre and array 1, to cycle all the students into bd. >

I tried several codes and I did not get anywhere, this was the last one I tried; include ("includes \ ligacaobd.php"); $ file = ('students.txt'); $ separator=""; // What separates results in TXT files?

if(file_exists($arquivo)){
  $fp=fopen($arquivo,'r');
  while(!feof($fp)){
    $line = trim(fgets($fp));
    if (empty($line)) {
     continue;
    }
    $lines = rtrim($line, ';'); //remover o ';' que tens no fim de cada linha
    $array = explode($separador, $lines); //separar por $separador

    $sql1 = "INSERT INTO aluno (numero, nome, processo) VALUES ('" . $array[0] . "', '" . @$array[1] . "', '" . @$array[2] . "')";
    $resultado1 = mysqli_query($conn,$sql1);

    if(!$resultado1){
     print "Falha na linha: " . $line;
    }
  }
  fclose($fp);

  print "Terminado";
}

Can you help me?

    
asked by anonymous 01.07.2016 / 03:12

1 answer

1

A simple example to get a better idea of how to do:

$data = file('tmp.txt'); // aqui vc coloca o caminho completo do arquivo txt.
// A função file() faz a leitura do arquivo e retorna cada linha num array.

// Monta a query SQL
// Será gerado um único INSERT com múltiplos valores.
// Dessa forma economizará invocando mysqli_query() apenas uma vez.
$query = 'INSERT INTO aluno (numero, nome, processo) VALUES ';
foreach ($data as $v) {
    $arr = explode(',', trim($v));
    $query .= PHP_EOL.'(\''.$arr[0].'\', \''.$arr[1].'\', \''.$arr[2].'\')';
}
$query .= ';';

// Teste para exibir na tela como foi gerada a query.
// Verifique se foi montado corretamente e então prossiga com o restante.
echo $query; exit;

// Considerando que $conn está com uma conexão ativa e tudo correto, então segue com a execução da query sql gerada acima
//$resultado1 = mysqli_query($conn, $query);

obs : In the original code of the question I noticed this passage

 @$array[1] . "', '" . @$array[2] 

Are you using error inhibitor because these indexes may be non-existent?
Regardless of the answer, I preferred to omit some treatment in the values obtained from the array because in the description of the question does not tell in detail what the rules of the business. Therefore, be aware that you need to process the data before you mount the query and especially before you submit it for execution.

    
01.07.2016 / 05:36