Explode lines of a textarea and separate them by commas

0

Opa,

I need to capture the textarea text, separate it by lines and then explode and separate it by commas.

        $lines = explode("\n", $respostas);
        $i = 0;
        if ( !empty($lines) )
        {
            foreach ($lines as $line)
            {
                $i++;
                    //Adiciona Respostas
                    foreach($respostas as $key)
                    {   
                        $sql = mysqli_query($conn, "INSERT INTO respostas
                            VALUES (
                                NULL, $i, '$key'
                        )");
                    }
                    //Adiciona Respostas

            }
        }

In the mysql insert, I need to save the contents ($ key) to the line ($ i), but it is duplicating the inserts according to the number of rows.

Textarea example:

teste, teste1, teste2
teste3, teste4
    
asked by anonymous 09.08.2016 / 15:01

1 answer

2

I made it here and I imagine it's what you want, see if it caters:

$respostas = "teste, teste1, teste2
        teste3, teste4";
        $lines = explode("\n", $respostas);
        $i = 0;
        if ( !empty($lines) )
        {
            $aWords = [];
            foreach($lines as $line){
                $aWords[] = explode(',', $line);
            }
            //Adiciona Respostas
            foreach($aWords as $key => $aWord2)
            {   
                $linha = ($key+1);
                foreach($aWord2 as $word){
                    $word = trim($word);
                    $query = "INSERT INTO respostas VALUES (NULL, $linha, '{$word}')\n";
                    echo nl2br($query);
                    //$sql = mysqli_query($conn, $query);
                }
            }
        }

The result looks like this:

INSERT INTO respostas VALUES (NULL, 1, 'teste')
INSERT INTO respostas VALUES (NULL, 1, 'teste1')
INSERT INTO respostas VALUES (NULL, 1, 'teste2')
INSERT INTO respostas VALUES (NULL, 2, 'teste3')
INSERT INTO respostas VALUES (NULL, 2, 'teste4')

Uncomment the $ sql line to insert into base or change as needed.

Good luck!

    
09.08.2016 / 16:18