这个板的新手,但到目前为止很喜欢它:)
我目前正在帮助我的一个 friend 重做她的个人网站,但我在表格的逻辑上遇到了困难。
该表应该在由 4 列/单元格/TDs pr 行(仅此而已)组成的表中显示最新消息 - 查找如下内容: http://screencast.com/t/Rh39oh6ms0OL
所以基本上我有一个从新闻表中选择日期、缩略图和标题的 SQL 查询(按 id desc 排序,所以我首先得到最新的)。
我已经做了一些逻辑(正如您在下面的代码中看到的那样),但它只会导致显示表格的第一行。 有谁能让我回到正确的轨道上吗?我们将不胜感激。
<table>
<?php
//PHP code used for building HTML table showing news-resumes
//Written by: Jesper Flindt
//Date: 2012.07.30
//Version: 1.0
//Getting data from MySQL database
$query = "select date, thumbnail, headline from news order by id desc";
$result = mysql_query($query) or die("Connection Error:" . mysql_error());
//Setting variables
$i = 0;
$p = 0;
//Starting row in table
print('<tr>');
//Looping through the resultset
while($row = mysql_fetch_assoc($result))
{
//Limit row to 4 cells (TDs)
if($i < 4)
{
//Display the date of the news as well as its thumbnail
print('<td><div style="padding-left:8px;"><b>Tilføjet d. '.$row['date'].'</b></div><div class="news_thumbframe"><img src="./upload/'.$row['thumbnail'].'" alt=""/></div></td>');
$i++;
$p++;
}
//If row is 4 cells wide, start new row
else if($i % 4 == 0)
{
print('</tr><tr>');
$i++;
$p++;
}
//Every second row should display the news headline as well as a "Read More" link ("Læs mere" in danish)
else if($i % 4 != 0 || $p % 4 == 0)
{
print('<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">Læs mere</a></div></td>');
$i++;
$p++;
}
else
{
$i = 0;
$p = 0;
}
}
?>
</table>
最佳答案
对于每个结果(即一个整个 新闻条目,而不是一列),您恰好执行了一个 if 子句,因为您使用了 if/elseif/elseif/else
构造。它们是互斥的。
含义:
这将完全跳过数据库结果的每四行:
else if($i % 4 == 0)
{
print('</tr><tr>');
$i++;
$p++;
}
这会捕获所有不是 4 的倍数和大于 4 的行:
else if($i % 4 != 0 || $p % 4 == 0)
{
print('<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">Læs mere</a></div></td>');
$i++;
$p++;
}
这永远不会执行:
else
{
$i = 0;
$p = 0;
}
因为你的其他条件已经穷尽了所有可能。
- 第一个子句将执行 4 次。
- 那么第二个子句会执行一次,因为
$i == 4
。 - 现在第三个子句将执行
$i == 5, 6, 7
- 第二个子句将执行
$i == 8
- 第三个子句将执行
$i == 9, 10, 11
等等等等
为什么有两个计数器变量?据我所知,你总是在相同的地方增加它们,并在相同的地方将它们设置为零。有什么区别?
更新
澄清您在评论中提到的内容:
else if($i % 4 != 0 || $p % 4 == 0)
||
表示逻辑或。它将首先检查第一个条件,如果条件不成立,它将检查第二个条件。如果其中任何一个为真,则整个条件都为真,子句将执行。
但是,当 $i % 4 == 0
为真时,$i % 4 != 0
仅为假。这意味着,执行了先前的 else if
子句。支票甚至不会到达 $p
部分。
关于php - 在 PHP + mysql 和 HTML 表中需要一些不合逻辑的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11739425/