Foreach running only once

Asked

Viewed 336 times

1

I have a code that reads a txt and writes the txt data in the database, only the foreach does not do the repetition and only writes the first line.

$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

$dados = file($arquivo_tmp);

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode('|', $linha);
    var_dump($valor);

$COD = $valor[1];
$NOME = $valor[2];
$CARACT = $valor[3];
$END = $valor[4];
$CPF = $valor[5];

$result_usuario = "INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES ('$COD','$NOME','$CARACT','$END','$CPF')";

$resultado_usuario = mysqli_query($conn, $result_usuario);

}

My txt is like this:

|42|Carlos Paiva da Silva|2|Av. Alameda Santos, 255|15265482536|

(not only is there a line in the file, it’s just an example)

  • João, post at least one example of the contents of the archive

  • @Rbz I updated the question with content.

  • @Joãomiguel iae, managed to solve?

2 answers

3

//Recebe os dados do formulario
$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

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

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode('|', $linha);

   $COD = $valor[1];
   $NOME = $valor[2];
   $CARACT = $valor[3];
   $END = $valor[4];
   $CPF = $valor[5];

   //prepara os values
   $result_usuario .=  "('$COD','$NOME','$CARACT','$END','$CPF'),";

}

//retira a ultima virgula
$values=substr($result_usuario, 0, -1);

//a query para inserir os dados no banco

    //$conn = ......

    $result_usuario = "INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES $values";

    $resultado_usuario = mysqli_query($conn, $result_usuario);

Bank table

ia tabela

txt file

arquivo txt

After running PHP code

após rodar php

A single INSERT statement ... VALUES can add multiple records to a table if you provide multiple lists of values. To do this, provide a list of values in parentheses for each record and separate the lists with commas.

For example:

"INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES
('42','Carlos Paiva da Silva 2','2','Av. Alameda Santos, 2','5265482532'),('43','Carlos Paiva da Silva 3','3','Av. Alameda Santos, 3','5265482533'), etc...

The statement shown creates records in the info table, assigning to the columns COD, NOME, CARACT, END, CPF of each record the values listed. The id column (if any) is not explicitly listed, so Mysql assigns a sequence value to that column in each record.

A multiple-line INSERT declaration is logically equivalent to a set of individual single-line statements. However, the multiple line declaration is more efficient because the server can process all lines at once instead of in separate operations. When you have many logs to add, multiple line statements provide better performance and reduce server load.

  • I tried to do it this way, and you didn’t even save at the bank.

  • 2

    @Joãomiguel, something wrong you did. See my edited reply. Maybe you forgot the connection string or run the INSERT statement

2


For identation your code should end after the var_dump:

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode('|', $linha);
    var_dump($valor);

But you don’t have the }; with this, (possibly) the block is closed at what would be the end of the method. Add the lock:

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode('|', $linha);
    var_dump($valor);
}

edited after comments

The variable $valores (after the explode) contains its actual list of items to be entered. I changed the variable name to make it more intuitive, see if you can resolve:

$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

$dados = file($arquivo_tmp);

foreach($dados as $linha){
    $linha = trim($linha);
    $valores = explode('|', $linha);
    var_dump($valores);

    foreach($valores as $valor){

        $COD = $valor[1];
        $NOME = $valor[2];
        $CARACT = $valor[3];
        $END = $valor[4];
        $CPF = $valor[5];

        $result_usuario = "INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES ('$COD','$NOME','$CARACT','$END','$CPF')";

        $resultado_usuario = mysqli_query($conn, $result_usuario);
    }
}

An alternative would be to create a string concatenating the values and giving only one Insert, since the first one works (yes, that’s gambiarra):

$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

$dados = file($arquivo_tmp);
$result_usuario = "";

foreach($dados as $linha){
    $linha = trim($linha);
    $valores = explode('|', $linha);
    var_dump($valores);

    $result_usuario = "INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES";
    foreach($valores as $valor){    
        $COD = $valor[1];
        $NOME = $valor[2];
        $CARACT = $valor[3];
        $END = $valor[4];
        $CPF = $valor[5];

        $result_usuario .= "('$COD','$NOME','$CARACT','$END','$CPF'),";
    }

    $result_usuario = substr($result_usuario, 0, -1); 

    $resultado_usuario = mysqli_query($conn, $result_usuario);
}
  • So the code would not end before entering the database?

  • before was without the last key =p if you give a count($dados), has more than one item to insert?

  • I had forgotten to add in question x) gave the Count and only resulted in the first line even, but in var_dump it returns me all lines!

  • then you need a new foreach, I’ll update the reply

  • It still didn’t work :/

  • var_dump($valor) within the second foreach shows correct values (enters more than once)? If yes, do not know what is wrong =/

  • If the values are being loaded, the problem should be in the SQL part

  • if it correctly inserts the first, I do not understand why it would make mistake in the others...

  • In the first code, if there are zillions of lines will make zillions of Inserts. In the second will generate this INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES('','','','',''),('2','','','',''),('a','r','l','o','s'),('','','','',''),('v','.',' ','A','l'),('5','2','6','5','4'),('','','','','')INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES('','','','',''),('3','','','',''),('a','r','l','o','s'),('','','','',''),('v','.',' ','A','l'),('5','2','6','5','4'),('','','','','')INSERT INTO info (COD, NOME, CARACT, END, CPF) VALUES ...............

  • I tried to do it this way, and you didn’t even save at the bank.

  • now the second code is correct! I won’t even test because it was almost the same as mine.

Show 6 more comments

Browser other questions tagged

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