How to split an array and write to the database in PDO

2

I have this code:

<?php
    foreach ($_POST as $dados =>$value) {
    $list = explode('_', $value);
    echo '<pre>' . print_r( $list, TRUE ) . '</pre>';
?>

It generates array output:

Array
(
    [0] => Manoel da Silva
)

Array
(
    [0] => [email protected]
)

Array
(
    [0] => (21)2481-3232
)

Array
(
    [0] => 41106
)

Array
(
    [0] => 21215430
)

But I want the output to be like this:

Array
(
    [1] => Manoel da Silva
)

Array
(
    [2] => [email protected]
)

Array
(
    [3] => (21)2481-3232
)

Array
(
    [4] => 41106
)

Array
(
    [5] => 21215430
)

After that, I want to save the values in the database, but something is going wrong:

$conn = conecta();

foreach ($_POST as $dados =>$value) {
    $cadastro = $conn->prepare('INSERT INTO clientes(:nome) VALUES $value');
    $cadastro->bindValue(':nome', $value); //to colocando um valor só...
    $cadastro->execute();
}

I want to enter the separate information in the bank, how do I do this?

    
asked by anonymous 18.05.2016 / 19:53

2 answers

2

It generates this unwanted output because it is always replacing the value of $list , that is, it will always print the $ list generated on the previous line:

I think this logic will be better:

$user = array();
foreach($_POST as $dado => $value) { // nota que mudei de dados para dado para ficar mais claro
   $list = explode('_', $value);
   $user[$dado] = $list[0]; // armazenamos cada dado (nome, telefone, etc..) dentro de um array
}
print_r($user);

You can also enter in the database soon:

foreach($_POST as $dado => $value) { // nota que mudei de dados para dado para ficar mais claro
    $cadastro = $conn->prepare('INSERT INTO clientes(' .$dado. ') VALUES :' .$dado); // nota que a chave do post ($dado) deve ser igual ao nome da coluna que tem na tabela em que vai inserir isto
    $cadastro->bindValue(':' .$dado, $value); //to colocando um valor só...
    $cadastro->execute();

}

Note that this is not the safest way to do this

    
18.05.2016 / 20:29
2

When using prepared statemens put the placeholders in the query, do not pass the values straight into sql and remember column names, tables can not be associated with placeholders only values.

Current code:

$cadastro = $conn->prepare('INSERT INTO clientes(:nome) VALUES $value');

To fix do

$cadastro = $conn->prepare('INSERT INTO clientes(nome) VALUES :nome');

To insert all values in a more practical way pass an array in execute() and use the queries as bind.

foreach($_POST as $dado => $value) {
   $valores = explode('_', $value);
   $binds = str_repeat('?,', 10) .'?';
   $cadastro = $conn->prepare('INSERT INTO clientes(nome,email,telefone,servico,cep,tipo_logradouro,logradouro,numero,complemento,ba‌​irro,cidade,estado) VALUES ('. $binds .')');
   $cadastro->execute($valores);
}
    
18.05.2016 / 20:29