txt file inserted in bd

Asked

Viewed 39 times

0

good, I am making a website, where you will find a txt file that the user will upload (always in msm format(process, name, number)). I’m trying to use arrays to search the data and enter it in the database. I can already search but I can’t put 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 make a cycle to insert all students in the bd.

I’ve tried a lot of codes and I’ve gotten nowhere, this is the last one I’ve tried; include("includes ligacaobd.php"); $file=('students.txt'); $separator = "; // What separates the results in the 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 help me?

1 answer

1

A simple example for you to have 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 understood this excerpt

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

Are you using error inhibitor because these indices 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 it does not inform with details what the business rules are. Therefore, be aware that you need to process the data before mounting the query and especially before sending it to execution.

Browser other questions tagged

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