How to split an array and write to the PDO database

Asked

Viewed 2,008 times

2

I have this code:

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

It generates the 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 way out:

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 record 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 that?

  • What is the original output? The format of the array you are running with foreach? Take an example and improve the display of the above sff code

  • I didn’t understand the question you have more fields to put information beyond the nome?

  • yes ray I have 11 fields:, I just did not put everything not to get too extensive the question:

2 answers

2

It generates this unwanted output because it is always overwriting the value of $list, ie, will always print the $list generated in 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 logo in the database:

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

  • continues in the array[0], all values: Array ( [name] => Array ( [0] => Manoel ) [email] => Array ( [0] => [email protected] ) ) each array with a different number and the precise q.

  • You’re right. I edited it in the exploding part. Sorry, that should do it. But what are you doing explodes? Give me an example. Don’t put True as the second element of print_r

  • I’m using explode to replace mysql split, actually I want to "separate" the values of the array to be able to insert in bd. The output is now like this : Array ( [name] => [email] => [phone] => [service] => 41106 [sCepDestino] => [num] => 48 [comp] => box 1 ) I think now you can insert the data separately, some hint in the Insert?

  • Wasn’t the array in that format you wanted? What if you don’t set it to explode and leave it alone $user[$dado] = $value;? Is that what you want?

2

When using Prepared statemens put the tags(placeholders) in the query, do not pass the values directly in sql and remember column names, tables cannot be associated with placeholders only values.

Current code:

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

To correct do:

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

To insert all values more practically pass an array in the execute() and use 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);
}
  • I did it ! output is now : Array ( [name] => Clayton Fields ) Array ( [name] => Clayton Fields [email] => [email protected] ) Array ( [name] => Clayton Fields [email] => [email protected] [phone] => (21)2481-3232 ) ,as I now insert each into a table field (INSERT) in PDO ?

  • here is the code: $list = array(); foreach($POST the $data => $value) { $list = explodes('', $value); $list[$data] = $list[0]; print_r($list). '<br />'; }

  • @Claytoncampos will be here shortly

  • @Claytoncampos always come the 11 fields?

  • Oops missed one , are 12 , are they: name, email, phone, service, zip code, street, street, number, complement, neighborhood, city and state.will be filled with the value of array that comes from the post, this is the idea.

  • @Claytoncampos that’s inside the $list after the explode() right?

  • does not come before: $list = array(); foreach($POST the $data => $value) { $list = explodes('', $value); $list[$data] = $list[0]; print_r($list). '<br />'; } the result comes from $value

  • @Claytonfields edited, see if the values go to the correct fields.

  • Warning: Pdostatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid Parameter number: number of bound variables does not match number of tokens in C: Program Files (x86) Easyphp-5.3.6.0 www Store test.php on line 108 ( $registration->execute($values);)

  • $valores has qtos elements?

  • place 13 elements, please.

  • @Is any claytoncampos empty? if not just leave like this $binds = str_repeat('?,', 12) .'?';

Show 8 more comments

Browser other questions tagged

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