2012-12-19 43 views
3

我試圖在PHP中向一個HTML表格顯示一個數組。但似乎有一個問題。我在學習PHP的過程中,在堆棧溢出中找到幾個示例,但是不適合我的情況。 什麼是顯示結果並將其結合到HTML表格中的最佳方式?謝謝大家在Html表格中顯示Php數組結果

這裏的控制器:

<?php include('inc/db_connect.php');?> 

<?php 
try 
{ 
    $sql = "SELECT id GroupName, VideoTITLE, ByArtist FROM videoclip"; 
    $result = $pdo->query($sql); 
} 
catch(PDOException $e) 
{ 
    $error = 'unable to fetch data: '.$e->getMessage(); 
    include'error.html.php'; 
    exit(); 
} 
$URLS = array(); 
while ($row = $result->fetch()) 
{ 
    $URLS[] = array('id' => $row['id'], 'GroupName' => $row['GroupName'], 'VideoTITLE' => $row['VideoTITLE'], 'ByArtist'=> $row['ByArtist']); 
} 

這裏的HTML表:

<div id="table_admin" class="span7"> 
     <h3>Videoclip List</h3> 

     <table class="table table-striped table-condensed"> 

       <thead> 
       <tr> 
       <th>Song name</th> 
       <th>Group name </th> 
       <th>Artist </th> 
       </tr> 
       </thead> 
      <?php foreach ($URLS as $URL){ 
       echo'<tbody>'; 
       echo'<tr>'; 
       echo'<td>'. $row['VideoTITLE']."</td>"; 
       echo'<td>'. $row['GroupName'].'</td>'; 
       echo'<td>'. $row['ByArtist'].'</td>'; 
       echo'<tr>'; 
       echo'</tbody>'; 
       } 
      ?> 


     </table> 

    </div> 

回答

8

你接近:

</thead> 
<tbody> 
<?php 
    foreach ($URLS as $URL){ 
     echo'<tr>'; 
     echo'<td>'. $URL['VideoTITLE']."</td>"; 
     echo'<td>'. $URL['GroupName'].'</td>'; 
     echo'<td>'. $URL['ByArtist'].'</td>'; 
     echo'<tr>'; 
    } 
?> 
</tbody> 

既然你服用的值$URLS數組並調用每個$URL您需要參考每行的值爲。不是您最初用於從數據庫結果填充數組的$row變量。請致電

僅供參考,您可能需要查看htmlentities()以逃避您的數據以防止XSS攻擊。

+0

謝謝,這是一個個人項目,我正打算消毒之後,我完成建設,只是爲了確保我瞭解它的權利。謝謝,愚蠢的錯誤,我從來沒有看到,只是糾正它 –

1

是的,正如約翰所說,你有$ URL作爲$ URL,但然後你引用一個數組調用每行$行。

的另一件事是,你可能要採取TBODY標籤的外每個循環

+0

謝謝,我只是正確的,這是一個愚蠢的錯誤 –

1

假設你的數據從fetchRow是好去,我只看到一個重要的錯誤在你的HTML:改變$行到您的foreach循環中的$ URL。此外,您還可以用HTML混合PHP讓它多了幾分漂亮:

<?php foreach ($URLS as $URL) { ?> 
    <tr> 
     <td><?php echo $URL['VideoTITLE']; ?></td> 
     <td><?php echo $URL['GroupName']; ?></td> 
     <td><?php echo $URL['ByArtist']; ?></td> 
    <tr> 
<?php } ?>