0

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?

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I was going to say, you should post that as the answer - I was over-complicating it as you gathered, I ended up just using $stmt->execute($_POST); and it was good to go. Thanks!
@Lauren Just be careful using $_POST as you cannot control what is in it.
I'm pulling it from an AJAX serialized array... does this undo the security measures that PDO offers?
@Lauren No, but any unexpected POST parameters will cause PDO to trigger an error / exception
1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.