【发布时间】:2017-01-16 14:07:54
【问题描述】:
我在 MySQL 的 JSON-type 列中得到以下数据:
{"2": [2, 3], "3": [29], "71": "test"}
我需要在属性“2”内搜索数组值,当变量放在查询中时效果很好,但在使用 PHP 的 PDO 数组时不行。
$field_id = 2;
$option_id = 2;
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '{\"$field_id\": $option_id }')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute();
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
// $used_qty returns 1 which is correct;
通过数组绑定返回0:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '?')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute(array('{"' . $field_id . '": ' . $option_id . '}"'));
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
无法弄清楚我在这里错过了什么。 请帮忙。谢谢。
【问题讨论】:
-
嗨,亚历克斯。当你得到答案时停止修改你的问题。它使答案看起来像一派胡言,对于可能找到您的问题并正在寻找类似答案的其他人来说毫无用处。