2013-11-02 100 views
0

我一直在試圖將我的數據庫的輸出分組爲時間段。PHP表按月拆分

例如

2013年5月

一些數據

更多數據

2013六月

一些數據

部分數據

下面的代碼在某種程度上可行,但即使應該有更多,也只會對每個月放一行數據。即每個月有不止一行數據

任何人都可以解釋爲什麼?

謝謝

function show_records($mysql_link) 
    { 
    date_default_timezone_set('Europe/London'); 
    $today=date('Y/m/d'); 
    $future=date('Y-m-d', strtotime("+10 months", strtotime($today))); 


    $q="SELECT number,startdate,traction,tourname,start,fares,tourcompany 
    FROM specials 
    WHERE startdate>='$today' AND startdate<='$future' AND steam='y' 
    ORDER BY startdate"; 


    $r=mysqli_query($mysql_link,$q); 
    $lastmonth=""; 
    if ($r) 
    { 


    echo "<Table id='customers'> 
    <tr> 
    <th>Date</th> 
    <th>Locomotive</th> 
    <th>Organiser</th> 
    <th>Name</th> 
    <th>Pick Up Points</th> 
    <th>Destination</th> 
    <th>Fares</th> 
    </tr>"; 


    while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC)) 
    { 
    $parts=explode('-',$row['startdate']); 
    $timestamp=strtotime($row['startdate']); 
    $parts2=date('YM',$timestamp); 

if (empty($lastmonth)|| $lastmonth!=$parts2) 
    { 

    if (!empty($lastmonth)) 
    { 
     echo '</table>'; 
} 
    echo "<h1>$parts2</h1>"; 
    echo "<table id='customers'>"; 
    $lastmonth=$parts2;    


     echo "<tr>"; 
     echo "<td>".$parts2."</td>"; 
     echo "<td>".$row['traction']."</td>"; 
     echo "<td>".$row['tourcompany']."</td>"; 
     echo "<td>".$row['tourname']."</td>"; 
     echo "<td>".$row['start']."</td>"; 
     echo "<td>".$row['end']."</td>"; 
     echo "<td>".$row['fares']."</td>"; 
     echo "</tr>"; 

     } 
    echo "</Table>"; 
    } 

    } 
    else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;} 
    } 
    show_records($mysql_link); 

    mysqli_close($mysql_link); 

    ?> 

回答

1

你只有$lastmonth != $parts2打印行的數據。請使用以下代碼:

if (empty($lastmonth) || $lastmonth != $parts2) { 
    if (!empty($lastmonth)) { 
     echo '</table>'; 
    } 
    echo "<h1>$parts2</h1>"; 
    echo "<table>"; 
    $lastmonth = $parts2; 
} 
echo "<tr>"; 
echo "<td>".... // and so on 
+0

已編輯的代碼。但是它仍然只顯示每個時間段的第一行 – user2635961

+0

你在'$ lastmonth = $ parts2'後面放了''''' –

+0

哦,並且改變'if(!empty){echo'';在這種情況下,'進入'echo'''。 –

0

在您的循環中,$ lastmonth變量僅在第一次更新。那麼你只是在尋找它是「空的」,它將不會在第一次更新之後。解決這個問題,我敢打賭它會很好用!