Reputation: 11
M saving the data in to db using json format such as example :
state_id city_id
["21"] ["32,35,67"]
And now want to search using mysql query(codeigniter) where state_id = 21 AND city_id = 32
.
Can any one please help me, While googling i found one stuff "json_extract" but it's unable to know how to use it in query.
Upvotes: 0
Views: 610
Reputation: 8288
using JSON_SEARCH
select * from `table` where JSON_SEARCH(`city_id`, 'all', '32') IS NOT NULL;
for codeigniter, simply use the query function -as i cant found another prober built-in way in codeigniter to do this- :
$results = $this->db->query('select * from `table` where JSON_SEARCH(`city_id`, "all", "' . $city_id . '") IS NOT NULL;');
Upvotes: 0
Reputation: 71
If I understood you correctly, this is the answer:
$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;
OUTPUT:
SELECT * FROM
table_name
WHEREstate_id
= 1 ANDcity_id
IN ( 1,2,3 );
Upvotes: 1