我正在建立一个网站,该网站使用一年中几个月的标签菜单,然后在每个月/标签内输入一个手风琴菜单,列出该月份发生的所有活动。
我在填充网站时使用PHP是新手,我在使代码工作时遇到了一些麻烦。 PHP之前的代码看起来像这样:
<div class="tabscontainer">
<div class="tabs">
<div class="tab selected first" id="tab_menu_1">
<div class="link">$Month</div>
<div class="arrow"></div>
</div>
</div>
<div class="curvedContainer">
<div class="tabcontent" id="tab_content_1" style="display:block">
<div id="page">
<ul id="example4" class="accordion">
<li>
<h3>$EventListGoesHere</h3>
<div class="panel loading">
<p>Some content here.</p>
</div>
</li>
</ul>
</div>
</div>
我尝试过使用while循环但是我一直在破坏我的代码。我试图使用的while循环是:
<?php
// Connects to your Database
mysql_connect("iphere", "username", "password") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
$data = mysql_query("SELECT * FROM MonthTable")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "My code here";
Nested SQL code to got through events table here.
}
?>
我想我的问题是,我是走正确的道路,如果是这样,有人可以让我知道标准代码应该如何适应PHP while循环吗?
我的数据库类似于:
MonthTable
ID | MonthShort |一个月的
1 | 2012Oct | 2012年10月
2 | 2012Sep | 2012年9月
事件表
ID | MonthID |事件
1 | 1 |婚礼
2 | 1 | Bar Mitzvah
3 | 1 |葬礼
4 | 2 |生日
5 | 2 |生日
6 | 2 |婚礼
非常感谢
答案 0 :(得分:1)
您只能进行一次查询。例如:
<?php
$sql = "
SELECT
a.id, b.id AS monthId, a.event, b.monthshort, b.monthlong
FROM
events_table_name AS a
INNER JOIN
month_table_name AS b ON b.id = a.monthId
ORDER BY
b.id, a.id ASC
";
// rest of db stuff here
$events = array();
$months = array();
while ($row = mysql_fetch_array($result)) {
if (! isset($events[$row["monthId"]])) {
$events[$row["monthId"]] = array();
}
$months[$row["monthId"]] = $row["monthlong"];
$events[$row["monthId"]][] = $row["event"];
}
for ($x = 1; $x <= 12; $x++) {
echo '<div class="tab" id="tab_$x">';
if (isset($events[$x])) {
echo '<div class="month-title">' . $months[$x] . '</div>';
echo '<ul>';
foreach ($events[$x] as $event) {
echo "<li>". $event ."</li>";
}
echo '</ul>';
}
echo '</div>';
}
?>
答案 1 :(得分:0)
你得到了什么错误?那个while循环很好。考虑使用mysqli。标准的mysqli循环是:
$db=new mysqli('host','user','pass');
$q=$db->query("SELECT * FROM db.table");
while ($f=$q->fetch_assoc()) {
print_r($f);
// echo "<br>";
}
试试这个,它会显示你为循环的每一行得到的数组。再一次,你得到了什么错误?