How to save array to db?

Asked

Viewed 844 times

2

I have 4 fields and wish to save in a db, however when putting in foreach ($_post['name'] as $name)... I do not know how to add more..

**DB**
id | vt | nome | qtn | id_cat
1  | 23 | qua..| 58  | 4
2  | 36 | não..| 57  | 2

register

<form action="php/cad.php" method="post">
    <label>
        <input type="button" class="btn btn-default" name="add" value="Add" />
    </label>
    <label>vt:</label>

    <fieldset id="inputs_adicionais"></fieldset>

    <input type="submit" value="Cadastrar" class="btn btn-default">
</form>

<script type="text/javascript">
    $(document).ready(function(){

        var input = '<label>Nome: <input type="text" name="vt[]" /> <input type="text" name="nome[]" placeholder="Nome"> <input type="text" name="qtn[]"  placeholder="Qtn"> <input type="text" name="id_cat[]" placeholder="id cat"> <a href="#" class="remove">X</a></label>';

        $("input[name='add']").click(function( e ){
            $('#inputs_adicionais').append( input );
        });

        $('#inputs_adicionais').delegate('a','click',function( e ){
            e.preventDefault();
            $( this ).parent('label').remove();
        });

    });
</script>

db

<?php
    include "conexao.php";

    $vt = $_POST['vt'];
    $nome = $_POST['nome'];
    $qtn = $_POST['qtn'];
    $id_cat = $_POST['id_cat'];

    $sql = "INSERT INTO produto(vt, nome, qtn, id_cat) VALUES ('$vt', '$nome', '$qtn', '$id_cat')";
    $query = $con->query($sql);

    if($query!=null){
        print "<script>window.location='../inicio.php';</script>";
    }
?>
  • 1

    I don’t understand, I could explain better?

  • I added the full code. I have several fields to add and I would like to do this without having to register 1 by 1, so I need to register several and just click 1 time in "Register".

  • Will record a name per record or will record them all in one column (not a good idea)

  • DB:id | vt | name | qtn | id_cat New column will be created with its respective vt, name, qtn, id_cat.. In a form I will insert -> vt, name,qtn,id_car, click to add more and add more -> vt,name.... Then I register them all at once, each in its respective column

1 answer

3


Example of how to mount an Insert with multiple values instead of generating an Insert for each loop repetition.

Comments of what makes the script are embedded in the code.

Note that there is no validation of receiving $_POST as this is not the focus of the issue, but I suggest you do a minimal treatment to avoid errors.

<?php
include "conexao.php";

/*
O laço de repetição prioriza o campo "nome". Se existir outro campo com um array maior, os arrays excedentes em relação aos arrays do campo "nome" serão ignorados.

Isso não é uma regra geral. É apenas um exemplo de como poderá tratar os dados.
*/ 
foreach ($_POST['nome'] as $k => $v) {
    $p = 'vt';
    // Se vt for não existir nesse índice do array, receberá valor vazio
    if (!isset($_POST[$p][$k])) {
        $_POST[$p][$k] = '';
    }
    $$p = $_POST[$p][$k];

    $p = 'qtn';
    // Se qtn for não existir nesse índice do array, receberá valor ZERO
    if (!isset($_POST[$p][$k])) {
        $_POST[$p][$k] = '0';
    }
    $$p = $_POST[$p][$k];

    $p = 'id_cat';
    // Se id_cat for não existir nesse índice do array, receberá valor vazio
    if (!isset($_POST[$p][$k])) {
        $_POST[$p][$k] = '';
    }
    $$p = $_POST[$p][$k];

    $values[] = "('$vt', '$v', '$qtn', '$id_cat')";
}

$sql = 'INSERT INTO produto(vt, nome, qtn, id_cat) VALUES  '.implode(PHP_EOL.', ', $values);

$query = $con->query($sql);
if($query!=null){
    print "<script>window.location='../inicio.php';</script>";
}
?>

Browser other questions tagged

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