user3973427
user3973427

Reputation: 1435

PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I am getting the error message:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/calendar/insert.php on line 17

but I don't understand what I am doing wrong.

I have an INSERT statement using 6 binds and I am binding 6, so where is the mismatch?

Code

Insert

$stmt = $dbh->prepare("INSERT INTO bookings (forename, surname, badge, department, start, end) VALUES (:forename, :surname, :badge, :department, STR_TO_DATE(:dp1,'%Y-%m-%d'), STR_TO_DATE(:dp2,'%Y-%m-%d'))");

Binds

foreach ($_POST as $key => $value) {
  $stmt->bindParam('$key', $value);
  echo "Binding $key as $value <br>";
}

which outputs:

Binding forename as John
Binding surname as Doe
Binding badge as 1 
Binding department as Days 
Binding dp1 as 2014-10-06 
Binding dp2 as 2014-10-10 

Upvotes: 0

Views: 510

Answers (2)

meda
meda

Reputation: 45490

  • No need for single quotes '
  • No need for colon :
  • use bindValue instead

foreach ($_POST as $key => $value) {
    $stmt->bindValue($key, $value);
}

Upvotes: 0

Kevin
Kevin

Reputation: 41885

Since you're using single quotes, the variables are not interpolated, you need to change them to double quotes:

foreach ($_POST as $key => $value) {
  $stmt->bindParam(":$key", $_POST[$key]); // assuming $key matches those named placeholders

}

Edit: A good insight regarding comments as eloquently stated @marc, you're getting the last value by just using $value.

Upvotes: 2

Related Questions