简体   繁体   中英

pdo and inserting json encoded to json field

I was following this guide... mysqltutorial.org/mysql-json

...and I decided to try theese concepts with PDO... but I must have lost something somewhere.

THIS works perfectly:

$db = new PDO ("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$array=array(1=>array(2=>'kkk',3=>'pizza'));
$json= json_encode($array); 

$db->query("INSERT INTO test(config) VALUES('".$json."');");

BUT THIS DON'T:

$db = new PDO ("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$array=array(1=>array(2=>'kkk',3=>'pizza'));
$json= json_encode($array); 

$sql = "INSERT INTO test (config) VALUES(':config');";
$stmt = $db->prepare($sql);
$stmt->bindParam(':config', $json, PDO::PARAM_STR);

$stmt->execute();

The second one returns this error:

SQLSTATE[22032]: <>: 3140 Invalid JSON text: "Invalid value." at position 0 in value for column 'test.config'.

var_dump on $json:

page.php:18:string '{"1":{"2":"kkk","4":"pizza"}}' (length=29)

What am I doing wrong? I don't get it.

You don't put quotes around placeholders. If you quote it, it tries to insert that literal string, instead of replacing it with the value from bindParam() .

$sql = "INSERT INTO test (config) VALUES(:config);";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM