2

I'm using the following php pdo code to insert data into mysql database, the insertion succeeded, however, the updated database is showing the string literals ':a', ':b' as values in respectively field. what's wrong?

  
$data = array(
  array('a' => 'John', 'b' => 'OK'),

);
    $st=$dbh->prepare("insert into mytable (a, b) values(':a', ':b')");
    $st->execute($data) or print_r($st->errorInfo());
user121196
  • 30,032
  • 57
  • 148
  • 198

3 Answers3

2

Remove the quotes from your placeholders. Otherwise, they are treated as string literals and directly inserted.

$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");

And remove the nesting on your array:

// $data is an associative array, it should not contain another array!
$data = array('a' => 'John', 'b' => 'OK');

To be consistent, I prefer to use the : on the placeholder array keys:

$data = array(':a' => 'John', ':b' => 'OK');    
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
1

You need to define your array the same in the sql and the parameters, you're missing the ":". You also don't need two arrays, only one.

$data = array(':a' => 'John', ':b' => 'OK');

The query also does not need quotes, since PDO already knows it's a parameter

$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
$st->execute($data) or print_r($st->errorInfo());
Developer
  • 2,021
  • 12
  • 11
0

You are executing a prepared statement with named placeholders. So, you need to remove quotes from your placeholders, otherwise they are treated as a values for respective columns and directly updated.

To be consistent, I prefer to use the : on the placeholder array keys:

$data = array(':a' => 'John', ':b' => 'OK'); 

$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");

You can also execute a prepared statement with question mark placeholders:

$data = array(
  array('John','OK'),

);
$st=$dbh->prepare("insert into mytable (a, b) values(?, ?)");
$st->execute($data) or print_r($st->errorInfo());
Pradeep Rajput
  • 724
  • 7
  • 11