doubei8541 2017-01-04 19:38
浏览 47
已采纳

在循环中向sql查询发送两个值

This is the screenshot of table order_items This is the screenshot of table <code>order_items</code>

Code

<?php
$aa = "SELECT * FROM `order_items` WHERE `id` = '$id'";
$result= $mysqli->query($aa);

while($ord = $result->fetch_assoc()) {
    $bb = "SELECT * FROM `products` WHERE `id` = ".$ord['product_id'];
    $results = $mysqli->query($bb);
    $obs = $results->fetch_assoc()
?>
<tr>
    <td>
        <?php echo $obs['name'];?>
    </td>
    <td>
        <?php echo $obs['code'];?>
    </td>
    <td>
        <?php echo $ord['quantity'];?>
    </td>
<?php }?>

There are two tables order_items and products. In the table order_items there are different product_id to the same order_id.

The above code is working properly if there is one product_id related to one order_item but if there are more than one product_id related to one order_item then this code is not working.

  • 写回答

1条回答 默认 最新

  • dongyan8929 2017-01-04 20:30
    关注

    You should join the two queries into one. And when querying the order_items table, you should be testing the order_id column to get all the products in an order.

    You should also use a prepared query to avoid SQL-injection.

    $sql = "SELECT p.name, p.code, oi.quantity
            FROM order_items AS oi
            JOIN products AS p ON p.id = oi.product_id
            WHERE oi.order_id = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($name, $code, $quantity);
    while ($stmt->fetch()) {
    ?>
    <tr>
        <td>
            <?php echo $name;?>
        </td>
        <td>
            <?php echo $code;?>
        </td>
        <td>
            <?php echo $quantity;?>
        </td>
    <?php }?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置