I have 2 tables in my DB - Categories and Products. In products table, I am using a foreign key field named category_id which contains comma separated category ids to which that product belongs to. Now I am using a multi select drop down using which the admin can select multiple categories for which that product belongs to. Now while editing the product, I want to display all the categories from categories table along with the selected categories for that particular product should be marked as selected. My query is something like below but my problem is that it repeats the categories values multiple times. I dont want to repeat the values. Any help would be appreciated.
<?PHP
$query_product = "SELECT * from cmco_products where product_id=$product_id";
$res_product = mysqli_query($conn, $query_product) or die(mysqli_error($conn));
$numrows = mysqli_num_rows($res_product); //check if the record existis into the DB
if($numrows > 0) //if the record exists into the DB
{
$row_product = mysqli_fetch_object($res_product);
$cat_id = explode(",", $row_product->category_id);
?>
<select class="form-control show-tick" name="multi_categories_id" id="multi_categories_id" multiple>
<?php
$query_categories = "SELECT * from cmco_categories order by date_created desc";
$res_categories = mysqli_query($conn, $query_categories) or die(mysqli_error($conn));
$x = 1;
while($row_categories = mysqli_fetch_array($res_categories))
{
foreach($cat_id as $key => $val)
{
$vals[$key] = trim($val)."<br />";
$qry_cat = "SELECT * from cmco_categories where category_id =".trim($val);
$res_cat = mysqli_query($conn, $qry_cat) or die(mysqli_error($conn));
$row_cat = mysqli_fetch_array($res_cat);
?>
<option value="<?php echo $row_categories['category_id']; ?>" <?php if($row_categories['category_id'] == trim($val)) { echo "selected";} ?>><?php echo $row_categories['category_name']; ?></option>
<?php
}
}
?>
</select>
<?PHP
}
?>
Thanks