2011-04-17 177 views
0

我有一個腳本來打印來自mysql數據庫的約會,有2個foreach循環,一個打印日期,一個打印與該日期相關的約會。但是第二個foreach循環只打印每個日期的第一個項目。嵌套的foreach問題

<?php 
error_reporting(0); 
session_start(); 
require('sessions.inc.php'); 
Include('config.inc.php'); 

if(!isLoggedIn()) 
{ 
    echo("not logged in"); 
} 
else 
{ 
//form 
    echo(' <html> 
     <center><h1>Add new Appontment</h1></center> 
     <form name="login" action="diary.php" method="post"> 
     Date (YYYY-MM-DD): <input type="text" name="date"/><br> 
     Time (HH-MM-SS):<input type="text" name="time"/><br> 
     Description:<input type="descrip" name="descrip"/><br> 
     Place:<input type="place" name="place"/><br> 
     <input type="submit" value="sumbit"/> 
     </form> 
     </html> 
     '); 

//Connect to DB 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
mysql_select_db($dbname); 


//Get Data from DB 

$query = "SELECT id,title,date,time,place FROM tbl_diary GROUP BY date;"; 
$result = mysql_query($query) or die(mysql_error()); 

//Get Data from form 
$date = mysql_real_escape_string($_POST['date']); 
$time = mysql_real_escape_string($_POST['time']); 
$descrip = mysql_real_escape_string($_POST['descrip']); 
$place = mysql_real_escape_string($_POST['place']); 

//insert into DB 
if (isset($_POST['date'],$_POST['time'],$_POST['descrip'],$_POST['place'])) 
{ 
    $insert = "INSERT INTO tbl_diary (date,time,title,place) VALUES ('$date','$time','$descrip','$place')"; 

     if (!mysql_query($insert)) 
     { 
      die('Error: ' . mysql_error()); 
     } 
    echo ('New appontment at'.$_POST['place'].'added, On'.$_POST['date'].".<br>"); 
    echo ('<a href="./index.php?page=diary">Please click to reload page</a>'); 
} 

//Intizlize array 
$array = array(); 


//Display appontments 


while($input = mysql_fetch_array($result)) 

{ 
    if (!isset($array[$input['date']])) 
    { 
     $array[$input['date']] = array(); 
    } 
    //put to end of array 
    $array[$input['date']] []= $input; 
} 
//The first for each prints each date, The second prints the times. 
foreach ($array as $TheDate => $items) 
{ 
$therealdate = date("d-m-Y", strtotime($TheDate)); 
//welcome to europe MySql 

    echo '<h1>'.$therealdate.'</h1>'; 
    echo "<ul>"; 

    foreach ($items as $item) 
    { 
     echo "<li>{$item['time']}: {$item['title']} "."@ {$item['place']}</li>"; 
    } 

echo "</ul>"; 
} 
//exit 
echo ('<a href="./main.php">Return to main</a>'); 
} 
?> 
+0

實際上只是解決了這個問題,它的加入GROUP BY日期的SQL查詢,廣東話的工作如何刪除這個雖然... – aaaa 2011-04-17 04:54:52

+1

應該是問題下方的刪除鏈接除非它的n00bz被禁用:) – 2011-04-17 04:56:41

+0

@Andrew,該代碼可以使用一些清理。 echo不是函數,include/require應該用作函數。 **聳肩** – Khez 2011-04-17 05:00:23

回答

1

你的mysql查詢字符串有問題。

SELECT id,title,date,time,place FROM tbl_diary GROUP BY date; 

如果日期相同,此查詢只抓取一行。

試試這個:

SELECT id,title,date,time,place FROM tbl_diary;