我正在尝试将我的 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/