[英]pdo and inserting json encoded to json field
I was following this guide... mysqltutorial.org/mysql-json 我正在按照这个指南... mysqltutorial.org/mysql-json
...and I decided to try theese concepts with PDO... but I must have lost something somewhere. ......我决定用PDO尝试这些概念......但我必须在某个地方丢失一些东西。
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: $ json上的var_dump:
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()
. 如果引用它,它会尝试插入该文字字符串,而不是用bindParam()
的值替换它。
$sql = "INSERT INTO test (config) VALUES(:config);";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.