2012-04-11 56 views
0

所以我有這個代碼組成了一個時間表網格(天和時間),我連接到數據庫,並選擇表,你可以看到...我在做什麼是例如,如果班級英語在星期一的09:00開始,我想將這些信息插入網格,我怎麼能實現這一目標呢?非常感謝插入值到網格-php,sql

<?php 
error_reporting(E_ALL); 
mysql_connect('db','user','password') 
    or die(mysql_error()); 
mysql_select_db('db') 
    or die(mysql_error()); 
$sql = "select day,start,class,time 
    from event where class='english'"; 
$res = mysql_query($sql) 
    or die(mysql_error()); 

    $days = array('Monday','Tuesday','Wednesday','Thursday','Friday'); 
$times= array('09','10','11','12','13','14','15','16'); 
echo "<table id='grid'>\n"; 
echo "<tr><td></td>"; 
for($t=0;$t<count($times);$t++) 
    echo "<th>$times[$t]:00</th>"; 
echo "<tr>\n"; 
for($d=0;$d<count($days);$d++){ 
    print "<tr><th>$days[$d]</th>"; 
    for($t=0;$t<count($times);$t++) 
    echo "<td id='td_$days[$d]_$times[$t]'></td>"; 
    echo "</tr>\n"; 
} 
echo "</table>\n"; 
?> 

回答

0

全部使用的foreach()首先爲您的陣列

foreach($times as $time) 
    echo "<th>$time:00</th>"; 

其次,不要亂用PHP的HTML,你一樣可以。至少所有這些使得你的代碼更清潔。 對於數據庫結果,你應該使用mysql_fetch_array();

比走這條路:

<table id='grid'> 
    <tr> 
     <td></td> 
     <?php 
      foreach ($times as $time) 
       echo "<th>$time:00</th>"; 
     ?> 
    <tr> 
     <?php 
      foreach ($days as $day){ 
       echo "<tr><th>$day</th>"; 
       foreach ($times as $time){ 
        $english = ($day == $res['day'] && $time == $res['time']) ? $res['class'] : ''; 
        echo "<td id='td_$day_$time'>{$class}</td>"; 
       } 
      } 
     ?> 
    </tr> 
    </table> 
+0

似乎有與表的錯誤? – ppaul 2012-04-11 13:41:21