donglou1866 2017-06-08 03:24
浏览 94
已采纳

PHP foreach循环以使用排除某些结果的值填充下拉列表

I have two tables. Enrollment and Product. I want to list Product on a <select>.

Within this <select>, I only want certain Product items to appear, whereby the condition is to read from Enrollment table's ProductID which is a foreign key to Product table.

How does one exclude certain results in a <select> that had already existed in a different table?

<?php
    $sql = 'SELECT * FROM product ORDER BY ProductID ASC';
    $result_select = mysql_query($sql);
    $rows = array();
    while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
    echo "<div class=\"spanstyle\">Add course/product:<select name='add_product'>";
    echo "<option selected>Choose here</option>";
    foreach ($rows as $row) {
        echo "<option value='" . $row['ProductID']."'>" . $row['ProductName']."</option>";
    }
    echo "</select></div>";
    $select1 = $_POST['add_product'];
    if (!strpos($select1, 'Choose here')) {
        $sql3="INSERT into enrollment (StudentID, ProductID) VALUES ($StudentID, $select1)";
        mysql_query($sql3);
        }
?>
  • 写回答

1条回答 默认 最新

  • doucong8553 2017-06-08 03:30
    关注

    First reaction is that you need to modify your SQL query here, not the PHP loop. Something like (and this is a quick first shot so don't trust it without testing)

    SELECT * FROM product WHERE ProductID NOT IN (SELECT ProductID from enrollments) ORDER BY ProductID ASC

    This would exclude any row in product whose ProductID also appears in the enrollments table.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀