Insert JSON value is failed
demyan112rv opened this issue · comments
When i try to insert json
value in my table
Amp\Loop::run(function () {
$db = Amp\Mysql\pool("...");
yield $db->query("CREATE TABLE IF NOT EXISTS amp_json (a INT(10), b JSON)");
/** @var \Amp\Mysql\Statement $statement */
$statement = yield $db->prepare("INSERT INTO amp_json (a, b) VALUES (?, ?)");
foreach (range(1, 10) as $num) {
$json = json_encode(['num' => $num]);
yield $statement->execute([$num, $json]);
}
$db->close();
});
I get an error:
Fatal error: Uncaught Amp\Mysql\QueryError: MySQL error (3144): #22032 Cannot create a JSON value from a string with CHARACTER SET 'binary'. Current query was INSERT INTO amp_json (a, b) VALUES (?, ?) in /vendor/amphp/mysql/src/Internal/Processor.php:617
I was able to insert a row with json
value only by concatenating, but it's not good solution.
yield $db->execute("INSERT INTO amp_json (a, b) VALUES ($num, '" . json_encode(['num'=>$num]) . "')");
May be you have some ideas about it?
Does an explicit conversion in your query work? INSERT INTO amp_json (a, b) VALUES (?, CONVERT(? USING utf8mb4))
I could run your reproduce script without problems though - maybe you've messed your encoding up,, were you running the connection as binary? (Default is utf8mb4_general_ci)
@bwoebi thanks for the quick reply!
I added to create
query SET utf8mb4 COLLATE = utf8mb4_unicode_ci
and replace ?
to CONVERT(? USING utf8mb4)
in insert
query.
This code is working good!
Amp\Loop::run(function () {
$db = Amp\Mysql\pool("...");
yield $db->query("CREATE TABLE IF NOT EXISTS amp_json (a INT(10), b JSON) CHARACTER SET utf8mb4 COLLATE = utf8mb4_unicode_ci;");
/** @var \Amp\Mysql\Statement $statement */
$statement = yield $db->prepare("INSERT INTO amp_json (a, b) VALUES (?, CONVERT(? USING utf8mb4))");
foreach (range(1, 10) as $num) {
$json = json_encode(['num' => $num]);
yield $statement->execute([$num, $json]);
}
$db->close();
});