在HTML表格中显示PHP数组结果 [英] Display Php Array result in an Html table

查看:103
本文介绍了在HTML表格中显示PHP数组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在php中将一个数组显示到HTML表中,但是存在问题.我在堆栈溢出中找到了几个示例,但是它们不适用于我的情况.

I was trying to display an array in php to an HTML table but there's an issue. I found several examples here in stack overflow, but they don't work for my case.

控制器:

<?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>

推荐答案

您将关闭:

</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,因此需要为每行的值引用$URL.不是最初用于从数据库结果填充数组的$row变量.

Since you're taking the values of the $URLS array and calling each one $URL you need to refer to $URL for each row's value. Not the $row variable you originally used to populate the array from the database results.

仅供参考,您可能需要研究 htmlentities() 来转义数据以提供帮助防止XSS攻击.

FYI, you may want to look into htmlentities() to escape your data to help prevent XSS attacks.

这篇关于在HTML表格中显示PHP数组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆