How to insert data in the database (mysql) received from an HTML form separated by commas?

1

Good evening, I'm going to receive information from a TEXTAREA html, and I need to get this in PHP and insert this information in the bank, how can I do that?

The information comes from TEXTAREA as follows:

0001, Student A, 10, 10, 20
0002, Student B, 8, 8, 16

The information already comes separated by commas, if it was in a TXT or CSV file I already saw that I could insert through a LOAD DATA but in this case a user will type the text and submit through an HTML form ... .

    
asked by anonymous 14.11.2016 / 00:01

1 answer

1

If I understood your question. You want to separate this information to insert into the database.

If in the textarea the information comes jumping equal line is in your example, I would do so:

I would use the explode to separate the information, then create a unique string and upload the values to the database:

<?php 

    // aqui vem a informação do textarea
    $stringDoTextArea = $_POST['textArea'];

    // aqui eu inseri o <br /> para identificar que pulou linha
    $stringDoTextArea = nl2br($stringDoTextArea);

    // os dados agora são um array
    $dados = explode("<br />", $stringDoTextArea);

    // vamos criar a string que insere os dados no DB
    $stringDeInsercao = "INSERT INTO tabela('campo1', 'campo2', 'campo3', 'campo4') VALUES ";

    while($d = 0; $d < count($dados); $d++){

        // concatena linha por linha
        $dadoX = explode(",",$dados[$d]);
        $stringDeInsercao .= "('".$dadoX[0]."', '".$dadoX[1]."', '".$dadoX[2]."', '".$dadoX[3]."') ,";

    }

    // aqui eu retiro a ultima virgula
    $stringDeInsercao = substr($stringDeInsercao, 0, -1);

    // insere os dados de uma vez só
    mysqli_query($conexao, $stringDeInsercao);

?>

This is just an example as there are several ways to do it.

    
14.11.2016 / 01:45