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

Asked

Viewed 229 times

1

Good evening, I will receive information coming from a TEXTAREA html, and I need to receive this in PHP and insert this information into the database, how can I do this?

The information comes from TEXTAREA as follows:

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

the information is already separated by comma, 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....

  • Take a look at this http://php.net/manual/en/function.implode.php

  • post the code, to verify, your question was not very clear

1 answer

1

If I understand your question. You want to separate this information to enter in the database.

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

It would use the explode to separate the information, then create a single string and raise the values in 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 one example because there are many ways to do.

Browser other questions tagged

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