0

我想将日历显示为特定月份的数据,它显示了该月的所有数据。

假设,我的数据库中有数据作为..

Jan=124;   Jan=243;   Jan=354
Feb=978;  Feb=765;   Feb=756;

它可以是:

Jan,2013
   124
   243
   354

Feb,2013
   978
   765
   756

我做了这个代码:

<?php
$q2="select * from  calendar";
$res2=mysql_query($q2);
$row2=mysql_fetch_assoc($res2);
$mnth = array('Jan','Feb');
$j= count($mnth);
for ($i=0; $i<= $j; $i++){
    if($row2['month']=='June'){ 
        ?><tr><td><?php 
        echo $row2['month']; ?> , <?php echo $row2['year']; 
        ?></td></tr><tbody><div><?php

        include("connection.php");
        $q1="select * from  calendar";
        $res=mysql_query($q1);

        while($row=mysql_fetch_assoc($res)){
            ?><tr><td><?php 
            echo $row['dates']; 
            ?></td></tr></tbody></div><?php 
        } 
    }
}
4

1 回答 1

2

每次您需要打印 HTML 标记时,我都会重新考虑中断 PHP。它使您的代码难以阅读。

此外,您正在循环中进行查询,这是一个坏主意,并且对于您的问题看起来完全没有必要。

<tbody>的循环中还有一个没有结束标签的开始</tbody>标签。

而且,正如@AleksG 在评论中提到的那样,您不应该使用mysql_*已弃用的函数。我建议切换到 PDO。

那么继续回答...

假设您的表结构如下所示:

+-------+------+-------+
| month | year | dates |
+-------+------+-------+
| Jan   | 2013 | 124   |
| Jan   | 2013 | 243   |
| Jan   | 2013 | 354   |
| Feb   | 2013 | 978   |
| Feb   | 2013 | 765   |
| Feb   | 2013 | 756   |
+-------+------+-------+

根据您的问题标题,这会将值放入一个数组中,键是月份和年份,值是数字“日期”字段:

// replace the below line with your mysql connection string
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$result = $dbh->query('
    SELECT month, year, dates FROM calendar ORDER BY year, month
');

$mnth = array();
foreach ($result as $row) {
    $key = $row['month'] .','. $row['year']; // e.g. 'Jan,2013'
    // push the new value. The inner array will be created automatically
    $mnth[$key][] = $row['dates'];
}

print_r($mnth);
/* will look like this:
Array(
    [Jan,2013] => Array(
        [0] => 124,
        [1] => 243,
        [2] => 354
    ),
    [Feb,2013] => Array(
        [0] => 978,
        [1] => 765,
        [2] => 756
    )
) */

但根据您的代码,您似乎希望将其输出为 HTML 表格。所以这就是你如何做到这一点。查询是相同的,所以这只是替换循环:

echo '<table>';
$current = '';
foreach ($result as $row) {
    // check to see if we've switched to a new month/year
    $next = $row['month'] .','. $row['year'];
    if ($current != $next) {
        // if we have moved to a new month/year, print a new header row
        echo '<tr><th>'. $next .'</th></tr>';
        // and update $current
        $current = $next;
    }

    echo '<tr><td>'. $row['dates'] .'</td></tr>';
}
echo '</table>';
于 2013-07-08T13:08:56.003 回答