foreach内部while循环

ccgok5k5  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(245)

我有两个表在我的数据库-类别和产品。在products表中,我使用了一个名为category\u id的外键字段,其中包含该产品所属的以逗号分隔的类别id。现在我使用了一个多选下拉列表,管理员可以使用它来选择产品所属的多个类别。现在在编辑产品时,我想显示categories表中的所有类别,以及该特定产品的所选类别应标记为选中。我的查询如下所示,但我的问题是它多次重复categories值。我不想重复这些值。任何帮助都将不胜感激。

<?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
}
?>

谢谢

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题