php - 在表中显示 MySQL 数据

标签 php mysql html-table

我正在尝试将我的 MySQL 数据库中的数据整齐地组织到表格中。我快完成了,但是在使用 while 循环时遇到了一些麻烦。

发布我的简单代码:

<link type="text/css" rel="stylesheet" href="style.css"/>

<?PHP 
$connect = mysql_connect("localhost","root","");

mysql_select_db("users");
$query = mysql_query("SELECT * FROM users");
    WHILE($rows = mysql_fetch_array($query)):

        $username = $rows['username'];
        $password = $rows['password'];
        $email = $rows['email'];

    echo "
    <table>
    <thead>
    <th>Username</th>
    <th>Password</th>
    <th>Email Adress</th>
    </thead>
    <tr>
    <td>$username</td>
    <td>$password</td>
    <td>$email</td>
    ";
    endwhile;
?>

这给了我这样的输出:

Username    Password    Email Adress

test           123  test@test.no

Username    Password    Email Adress

testies 123 testies@test.no

Username    Password    Email Adress

tested  12345   tested@test.no

这里明显的问题是我的标题是在 while 循环中打印的,因此我为每个条目都得到了新的标题。不过这看起来真的很愚蠢,我更希望标题只出现一次。关于如何执行此操作的任何想法?

我曾尝试在 while 循环之前用标题启动表格,但后来 <td> s 不会与标题宽度相对应,因为程序不会将它们识别为同一个表,因此不需要匹配。

最佳答案

使用这个

<link type="text/css" rel="stylesheet" href="style.css"/>

<?PHP 
$connect = mysql_connect("localhost","root","");

mysql_select_db("users"); ?>
<table>
    <thead>
    <th>Username</th>
    <th>Password</th>
    <th>Email Adress</th>
    </thead><?php 

$query = mysql_query("SELECT * FROM users");
    WHILE($rows = mysql_fetch_array($query)) { ?>                    
    <tr>
    <td><?php echo $rows['username']; ?></td>
    <td><?php echo $rows['password']; ?></td>
    <td><?php echo $rows['email']; ?></td>
    </tr>
<?php } ?>    
?>

关于php - 在表中显示 MySQL 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23384426/

相关文章:

mysql - 获取两个时间戳之间的范围

php - 前端 Controller 模式 - 路由器是前端 Controller 吗?

PHP: 日期时间帮助

mysql - MySql 与 ElasticSearch 中的聚合

Python Beautiful Soup Table 数据抓取特定 TD 标签

html - Angular 2 : Remove the wrapping DOM element in a component

html - 不需要的表格单元格填充

php - 多个 select2 在表单提交时仅返回一个选择

php - 寻找 CSS 优化器(php 脚本或在线服务)

php - 一次从多个 url 获取 XML 数据失败