How to mount key vaue array pair to insert into table?

Asked

Viewed 46 times

0

$key = "id,name";
$val = "'$lastid','$autor'";
...
if ($email){
   $key .= ",email";
   $val .= ",'$email'";
}
...
$keys = \explode(',', $key);
$vals = \explode(',', $val);
$arr  = array_combine($keys,array_fill(0,count($keys),$vals));
....
//O array montado fica assim:
// INSERT INTO autores (id, name, email) VALUES (:id, :name, :email)

$insok = $pdo->insert($arr);
if (!$insok) {
    $error = "Erro ao inserir dados<br>".print_r($conn->errorInfo());
}

echo $error; // mostra o seguinte resultado

//array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL }

I would like to know how to solve this mistake:

1 answer

0

Just keep it simple, you don’t need that array_fill() just call the array_combine() with $keys and $vals. If using Prepared statements do not include single quotes in the values.

Change:

$arr  = array_combine($keys,array_fill(0,count($keys),$vals));

For:

$arr  = array_combine($keys, $vals);

Your array will look like this:

Array
(
    [id] => '10'
    [name] => 'fulano'
)
  • Hello, thank you so much for the quick answer. The problem really was in the single quotes. The correct is: $key = "id, name"; $val = $id. " ," . $cauthor; E also simplified the array_combine() as you said. Worked ok. A hug.

  • @user1818765 with array_fill() gets like this: Array&#xA;(&#xA; [id] => Array&#xA; (&#xA; [0] => '10'&#xA; [1] => 'fulano'&#xA; )&#xA;&#xA; [name] => Array&#xA; (&#xA; [0] => '10'&#xA; [1] => 'fulano'&#xA; )&#xA;&#xA;)

Browser other questions tagged

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