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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测