在WHILE LOOP中设置适当的条件语句

时间:2013-09-11 13:56:07

标签: php while-loop conditional-statements

提交mysqli_query以从购物车数据库中选择打开/未履行订单后,结果将以标准WHILE LOOP输出到屏幕。

while($row = mysqli_fetch_array($oresult)) { include('orders-open.php');}

orders-open.php只是TABLE的内部部分:

 <tr style="color:#FFF;">
    <td><?php echo $row['Buyer']; ?></td>
    <td><?php echo $row['Cart_Date']; ?></td>
    <td><?php echo $row['Item_Number']; ?></td>
    <td><?php echo $row['Item_Title']; ?></td>
    <td><?php echo $row['Item_FPrice']; ?></td>
    <td><?php echo $row['Item_Qty']; ?></td>
    </tr>

所以这是我的问题,我想在$ row ['Buyer']中的值更改的位置处的记录之间应用一个简单的HTML“<HR>”标记,因此通过示例:

John Doe    9/11/13       123456     Item 1       $5.99     5
John Doe    9/11/13       123654     Item 2       $8.99     3
John Doe    9/9/13        321456     Item 3       $4.99     2

(HR - Horizontal Rule Tag here)

Mike Doe    9/7/13       123555     Item 1       $9.99     2
Mike Doe    9/7/13       123777     Item 2       $2.99     6

在WHILE LOOP中编写条件语句以将$ row [Buyer']结果与之前的$ row ['Buyer']结果进行比较的最佳方法是什么?

4 个答案:

答案 0 :(得分:1)

$first_run = TRUE;
$previous_buyer = NULL;
while($row = mysqli_fetch_array($oresult)) { 
      if($first_run) {
         $first_run = FALSE;
         $previous_buyer = $row['Buyer'];
      }
   include('orders-open.php');
}

然后在你的包含文件中:

<?php if($previous_buyer != $row['Buyer']) { 
    echo '<HR width="100%">'; 
    $previous_buyer = $row['Buyer'];
} ?>
<tr style="color:#FFF;">
    <td><?php echo $row['Buyer']; ?></td>
    <td><?php echo $row['Cart_Date']; ?></td>
    <td><?php echo $row['Item_Number']; ?></td>
    <td><?php echo $row['Item_Title']; ?></td>
    <td><?php echo $row['Item_FPrice']; ?></td>
    <td><?php echo $row['Item_Qty']; ?></td>
</tr>

答案 1 :(得分:0)

你可以这样做:

$buyer = null ;  //Cache buyer in a variable, because $row is reset in the loop.

while($row = mysqli_fetch_array($oresult)) {
   include('orders-open.php');
   if ($buyer !== $row["Buyer"]){
     echo ($buyer !== null) ? "<hr/>" : "" ;
     $buyer = $row["Buyer"] ;
   }
}

答案 2 :(得分:0)

$prev_buyer = '';
while($row = mysqli_fetch_array($oresult))
{
  if($prev_buyer !== $row['Buyer'])
  {
    //Do Something
  }

  include('orders-open.php');

  $prev_buyer = $row['Buyer']
}

答案 3 :(得分:0)

就像埃隆上面所说 - 改变这个:

while($row = mysqli_fetch_array($oresult)) { include('orders-open.php');}

$old_buyer = null;
while($row = mysqli_fetch_array($oresult)) {
    if ($row['Buyer'] != $old_buyer) {
        echo '<hr>';
    }
    $old_buyer = $row['Buyer'];
    include('orders-open.php');
}