Lauren
Lauren

Reputation: 785

Creating Array for PDO Execute Statement

I'm trying to dynamically create an array for the execute portion of a PDO insert. My working code includes text like this:

$stmt->execute(array(
  ':fname' => $_POST['fname'],
  ':lname' => $_POST['lname'],
  ':email' => $_POST['email']
));

My first attempt at creating an array:

$insert_execute = array();
foreach ($values as $column => $value) {
  array_push($insert_execute, ":" . $column . " => " . "'".$value."'");
}

But when I try to execute I get a PDO error:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

And when I print the result, there is an additional parameter:

Array
(
  [0] => fname => 'Test Name'
  [1] => lname => 'Test Last'
  [2] => email => '[email protected]'
)

How can I modify the array_push to remove the [0], [1], [2] etc. in the array?

Upvotes: 0

Views: 82

Answers (2)

Phil
Phil

Reputation: 164796

You seem to be overly complicating the matter. You already have an associative array of parameter names to values so you can simply use that

$stmt->execute($values);

The colon prefix (:) on the parameter names in the array is optional. If it's not there, the PDO extension will add it automatically.

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

You're building, and pushing, strings onto that array. => shouldn't be part of what you're inserting -- it's just for initialization.

What you mean to say:

foreach ($values as $column => $value) {
  $insert_execute[":$column"] = $value;
}

Upvotes: 1

Related Questions