使用json格式将数据保存到db,例如:
where state_id = 21 AND city_id = 32
现在想要使用mysql查询(codeigniter){{1}}进行搜索。
任何人都可以帮助我,谷歌搜索我发现一个东西“json_extract”但它无法知道如何在查询中使用它。
答案 0 :(得分:1)
如果我理解正确,这就是答案:
$json = '{"state_id": 21, "city_id": [32,35,67]}';
$decodedJson = json_decode($json, true);
/** @var $state_id int */
/** @var $city_id array */
extract($decodedJson);
$sql = printf("SELECT * FROM `table_name` WHERE `state_id` = %d AND `city_id` IN ( %s );", $state_id, join(',', $city_id));
echo $sql.PHP_EOL;
输出:
SELECT * FROM
table_name
WHEREstate_id
= 1 ANDcity_id
IN(1,2,3);
答案 1 :(得分:0)
select * from `table` where JSON_SEARCH(`city_id`, 'all', '32') IS NOT NULL;
对于codeigniter,只需使用查询函数 - ,因为我无法在codeigniter中找到另一个探测器内置方式来执行此操作 - :
$results = $this->db->query('select * from `table` where JSON_SEARCH(`city_id`, "all", "' . $city_id . '") IS NOT NULL;');