在Html表中显示Php Array结果

Obe*_*son 4 php

我试图在PHP中将数组显示为HTML表,但是存在问题.我在堆栈溢出中找到了几个例子,但它们对我的情况不起作用.

控制器:

<?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'] );
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Joh*_*nde 10

你很亲密:

</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>
Run Code Online (Sandbox Code Playgroud)

由于您正在获取$URLS数组的值并调用每个数组的值,因此$URL您需要参考$URL每行的值.不是$row您最初用于从数据库结果填充数组的变量.

仅供参考,您可能希望调查htmlentities()以逃避数据以帮助防止XSS攻击.