Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdo and inserting json encoded to json field

Tags:

json

php

mysql

pdo

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.

like image 971
Gwen Hufschmid Avatar asked Dec 06 '25 13:12

Gwen Hufschmid


1 Answers

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);";
like image 170
Barmar Avatar answered Dec 08 '25 02:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!