简体   繁体   English

一种简单的方法来打印内容,仅在while循环内一次?

[英]Easy method to print something, only once inside while loop?

I want to fetch information from one table and loop that until it's done, with the help of a while loop. 我想从一个表中获取信息,并在while循环的帮助下循环进行直到完成。 Although, I want one column to be printed only once inside the loop. 虽然,我希望在循环内只打印一次一列。

There's two solutions I've come up with... 我想出了两种解决方案...

<?php   
$i = 0;
// while loop start
if($i == 0){
// stuff to print
$i++;
}
// while loop end
?>

And ofcourse, I could just make another query before the while loop. 当然,我可以在while循环之前进行另一个查询。

But these methods really aren't too efficient. 但是这些方法确实效率不高。 Is there a less messy way to do this? 有没有那么麻烦的方式来做到这一点?

Actually, I'd be okay with running another query before the while loop, if it didn't get so messy, and perhaps if I could just re-use the query intended for the loop (I fetch everything from the table). 实际上,我可以在while循环之前运行另一个查询,如果它不会变得那么凌乱,或者如果我可以重用该循环的查询(我从表中获取所有内容)的话,我会没事的。 I tried experimenting with mysql_fetch_field, but I'm not sure I get how it works, or if that even helps here * embarrassed * 我尝试使用mysql_fetch_field进行实验,但不确定是否可以使用它,或者这是否有助于*尴尬*


Currently, the code looks like so: 当前,代码如下所示:

$fetch = mysql_query("SELECT *
                      FROM `pms`
                      JOIN `pm_conversations` ON pms.ConvID = pm_conversations.ID
                      WHERE `ConvID`='".$_GET['id']."'");

$i = 0;
while($print = mysql_fetch_array($fetch)){
  if($i == 0){
  echo $print['Subject'];
  $i++;
  }
  <table>
  <th><?=$print['From']?>, <?=$print['DateSent']?></th>
  <tr><td><?=$print['Message']?></td></tr>
  </table>
}

If I understand your question correctly, I think you've got the right idea. 如果我正确理解了您的问题,我认为您有正确的主意。 I'm guessing you want to print something extra the first iteration (like maybe column headers using the array keys)? 我猜您想在第一次迭代中额外打印一些内容(例如使用数组键的列标题)?

$cnt= 0;
while($row = mysql_fetch_assoc($res)) {
    if(0 == $cnt++) {
        // first iteration only
    }
    // all iterations
}

Or, if I'm totally off a better description of what you're trying to do and the real world situation would help. 或者,如果我完全不了解您要做什么,那么实际情况会有所帮助。

Have you thought about do...while? 您是否考虑过……而? It has all of the benefits of while, plus it allows for code to conditionally happen before the first iteration. 它具有while的所有优点,并且它允许代码在第一次迭代之前有条件地发生。

$res = mysql_fetch_array( $resource );
// run the magical run once query/functionality/bunnies/whatever
// Hey, I'm tired. Let there be bunnies.
do
{
    // put the regular while loop constructs in here;
}
while( $res = mysql_fetch_array( $resource ) );
$rs = mysql_query("SELECT * FROM tbl");
$row = mysql_fetch_array($rs);

do {
    echo $row['column_name'];
} while($row = mysql_fetch_array($rs));

I don't know if this is what you need. 我不知道这是否是您所需要的。 Hope this one helps. 希望这对您有所帮助。 =] =]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM