how to insert into the database a variable that brings an array?

1

I have a page that has a textarea and in this textarea the user will put a list of records and in that records I separate the strings with the function explode

this is my html index.php code

Active MTMs     #Login{         text-align: center;         margin: 0 auto;         padding: 40px 15px;     }

label{
    display: block;
    margin-right: 100px;

    padding: 5px;
}

#text{
    width: 500px;
    height: 480px;
}

    function valid () {         if (form.text.value == "") {             alert ('Fill in the field');             form.text.focus ();             return false;         }         alert ("Material required successfully!");     }

    alert ("test");

- >                           Material:             

        <label for="submit"></label>
        <input type="submit" name="enviar" class="input_button" id="bt_logar" value="enviar" />
    </form>

this is the insert.php code that contains the query

<?php 

    $conexao = @mysql_connect("localhost","root","") or print("erro");
    if (!$conexao) die ("<h1>Falha na conexao com o servidor!</h1>");
    $db = @mysql_select_db("test");
    if (!$db) die ("<h1>Falha na conexao com o Banco de Dados!</h1>");



    $text = $_POST["text"];
    //echo $text;

    $alterado = array("-");
    $alterar = array("");
    $replace = str_replace($alterado,$alterar,$text);   

    $novaString = chunk_split($replace,12,".");
    //echo $novaString;

    $bat = explode('.',$novaString);
    print_r($bat)."<br>";

    //insere normalmente
    $sql = @mysql_query("insert into test.tab_mtm_ativos (MTM,planta) values ('$bat','B510')  on duplicate key update mtm = values(mtm)") or die ("erro");

    @mysql_close($conexao, $sql);
    header('location: mtm.php');

?>
    
asked by anonymous 18.04.2016 / 00:07

1 answer

1

Well, in a relational database it is not possible to insert the array type into a table. You will have to insert as a string, what you can do is choose a string format that covers vectors, such as JSON or XML.

As a simple array, I advise you to convert to JSON before inserting into the database with the json_encode function, and every time you fetch that data, decode it with the json_decode function.

After exploding the array, code it like this:

 $bat = explode('.',$novaString);
 $bat = json_encode($bat);

This will make your $ bat array, turn a string, when you need to get it to use it as an array again, use:

$bat_array = json_decode($bat);

For more information, visit:

link

and

link

    
18.04.2016 / 00:30