【问题标题】:How do I add a line every 2nd query如何每第二个查询添加一行
【发布时间】:2014-03-17 18:03:28
【问题描述】:

所以下面的代码是创建一个 2 个并排的盒子,一个在右边,一个在左边。我现在需要开始一个新行,但不知道如何。 MySQL 为每个盒子换行,但我每第二个盒子都需要它......有什么想法吗?

图像显示了我需要在每一行重复的内容(代码现在的内容):

代码:

 <table width="90%" height="166" border="1" align="center" cellpadding="3" cellspacing="3">
  <tr>

<?
if (isset($_GET['id'])) {
    $proid = $_GET['id'];
    $result = mysqli_query($con,"SELECT * FROM auction_products WHERE id = $proid");
} else {
    $result = mysqli_query($con,"SELECT * FROM auction_products");  
}
while($row = mysqli_fetch_array($result))
  {
?>
<td width="50%">
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3" align="center">
<TD>
<p>Input : <? echo $row['barcode'] ?><br />
Barcode : Codabar<br />
Check Digit : N.A.<br /><br />

</p>
 </TD>
 <TD>
 |<br />
 |<br />
 |<br />
 |

</TD>
<TD>
Winner #______<br />
Amount $______
</TD>
</TABLE>
<center>
 <div id="barcodecontainer" style="width:5in">
 <div id="barcode<? echo $row['id']?>" ><? echo $row['barcode']?></div>
 </div>
<br />
<script type="text/javascript">
/* <![CDATA[ */
function get_object(id) {
    var object = null;
    if (document.layers) {
        object = document.layers[id];
    } else if (document.all) {
        object = document.all[id];
    } else if (document.getElementById) {
        object = document.getElementById(id);
    }
return object;
}
 get_object("barcode<? echo $row['id']?>").innerHTML=DrawHTMLBarcode_Code128B(get_object("barcode<? echo $row['id']?>").innerHTML,"yes","in",0,2.5,1,"bottom","center","","black","white");
/* ]]> */
</script>
</center>
</td>
<? } ?> 
</tr>
</table>

【问题讨论】:

  • 将所有代码从表格中间分离出来会有所帮助....
  • 你能解释一下Rottingham吗?我不知道那是什么意思。

标签: php mysql loops select


【解决方案1】:

简单的答案是这样的:

$i=0;
while($row = mysqli_fetch_array($result)){
    echo '<td>';
    /* Some code here */
    echo '</td>';

    if( $i++ &1==0 ){ echo '</tr><tr>' ;} // Start new line
}

魔法发生在 if 语句中,即按位比较,它检查二进制符号中的“一”是否等于 0。这只发生在 $i 的偶数倍上。

1&1 == 1 (1 in binairy is 001)
2&1 == 0 (2 in binairy is 010)
3&1 == 1 (3 in binairy is 011)
4&1 == 0 (4 in binairy is 100)
5&1 == 1 (5 in binairy is 101)
etc :)                      ^--- we use this to check

对于奇数/偶数,这是我所知道的最快的方法(我很想知道是否有更快的方法)。


这种方法对于奇数/偶数非常有效,但不适用于每个第 3、7、21 个等等。为此,我们有模数:

if( $i%7===0 ){ /* ... */ }

如果您减去最大数量的 7,则测试剩下多少整数。再举个例子:

7 % 2 === 1 (7-2-2-2 = 1, cant subtract another 2)
9 % 6 === 3 (9-6 = 3, cant subtract another 6)
9 % 2 === 1 (9-2-2-2-2 = 1, cant subtract another 2)
123 % 8 === 3 (123 -(15*8)=3, cant subtract another 8)

您可以将 $i%2 之类的模块用于奇数/偶数,但模数是一段昂贵的代码,仅在需要时使用。

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2018-03-20
    • 2015-01-10
    • 1970-01-01
    • 2019-05-29
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多