I have the following php code getting a list of numbers from a Database:
$current_product_id = "SELECT `product_id`,`category_id` FROM `oc_product_to_category` WHERE `product_id`='$product_id' ";
$current_product_ids = mysql_query($current_product_id);
$current_product_cat_ids='';
while($current_product_cat_id = mysql_fetch_array($current_product_ids)){
$current_product_cat_ids.=$current_product_cat_id['category_id'].',';
}
echo $current_product_cat_ids;
The code echos something like this: 84,109,140,146,151,152,
I would like to now take each of those numbers and somehow use them in another SQL query kinda like this:
$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path` WHERE `category_id`='84,109,140,146,151,152'"
So I can put the values into another SQL Query. Any ideas how I can do this? Thanks
Using the IN clause and the same variable:
$res = mysql_query("SELECT `category_id`,`path_id` FROM `oc_category_path` WHERE `category_id` IN (" . rtrim($current_product_cat_ids, ',') . ")");
while ($row = mysql_fetch_assoc($res)) {
print_r($row);
}
You're close. You can use MySQL's FIND_IN_SET()
or IN()
:
$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path`
WHERE FIND_IN_SET(`category_id`, '84,109,140,146,151,152')"
Or IN()
:
$parent_category_ids = "SELECT `category_id`,`path_id` FROM `oc_category_path`
WHERE `category_id` IN(84,109,140,146,151,152)"
SELECT
`category_id`
, `path_id`
FROM `oc_category_path`
WHERE `category_id` IN(84,109,140,146,151,152)
OR:
SELECT
`category_id`
, `path_id`
FROM `oc_category_path`
WHERE FIND_IN_SET(`category_id`, '84,109,140,146,151,152')
The first has no quotes, the second has quotes around the string that contains the comma-delimited list.
Standard SQL provides the IN
operator for matching a list of values.
SELECT `category_id`,`path_id`
FROM `oc_category_path`
WHERE `category_id` IN (84,109,140,146,151,152)
If the values come from a table, a subquery is an especially useful technique;
SELECT `category_id`,`path_id`
FROM `oc_category_path`
WHERE `category_id` IN (SELECT `cat_id` FROM cat_table WHERE active=true)