在我的PDO查询上重复

时间:2016-05-18 07:12:16

标签: php pdo

这是我的代码先生:

<?php
    session_start();
    include 'include/db_config.php';

    $result = $dbs->prepare("SELECT * FROM service_info ORDER BY id DESC");
    /*$result->bindParam(':id', $_SESSION['id']);*/
    $result->execute();
    for($i=0; $row = $result->fetch(); $i++){

    $result2 = $dbs->prepare("SELECT *FROM customer_info ORDER BY id DESC");
    $result2->execute();
    for($j=0; $row2 = $result2->fetch();$j++){


?>


<tr class="record">
    <td><?php echo $row2['firstname'];?></td>
    <td><?php echo $row['no_guest']; ?></td>
    <td><?php echo $row['type_service']; ?></td>
    <td><?php echo $row['datepicker']; ?></td>
    <td><?php echo $row['t_time']; ?></td>

    <td><a href="delete.php?id=<?php echo $row['id']; ?>"> delete </a></td>
</tr>
<?php
    }
}
?>

我没有使用LEFT JOIN来显示来自2个表的数据。我只是想以自己的方式去做。但我的问题是它复制了我的数据。在我插入第二个查询之前,它只有2个数据,现在已经是4个。我只是无法弄清楚复制发生在哪里。

请有人帮帮我。在此先感谢。

1 个答案:

答案 0 :(得分:0)

您在第二个for中显示数据,该数据位于第一个for内。因此,您获得customer_info表长度* service_info长度结果的结果计数。您应该在数组中保存信息,然后只使用一个for周期。例如:

    <?php
        session_start();
        include 'include/db_config.php';
        $services = array();
        $customers = array();
        $result = $dbs->prepare("SELECT * FROM service_info ORDER BY id DESC");
        /*$result->bindParam(':id', $_SESSION['id']);*/
        $result->execute();
        for($i=0; $row = $result->fetch(); $i++){
            $services[] = $row;
        }
        $result2 = $dbs->prepare("SELECT *FROM customer_info ORDER BY id DESC");
        $result2->execute();
        for($j=0; $row2 = $result2->fetch();$j++){
          $customers[] = $row2;
        }
        foreach($services as $key => $service) {
    ?>


    <tr class="record">
        <td><?php echo $customers[$key]['firstname'];?></td>
        <td><?php echo $service['no_guest']; ?></td>
        <td><?php echo $service['type_service']; ?></td>
        <td><?php echo $service['datepicker']; ?></td>
        <td><?php echo $service['t_time']; ?></td>

        <td><a href="delete.php?id=<?php echo $service['id']; ?>"> delete </a></td>
    </tr>
    <?php
        }
    ?>
是的,我建议您使用不同的方法,例如joins