我正在尝试将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不会与标题宽度对应,因为程序不会将它们识别为同一个表,因此不会需要匹配。
答案 0 :(得分:2)
使用此
<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 } ?>
?>
答案 1 :(得分:0)
按如下方式更改您的代码。
<?PHP
$connect = mysql_connect("localhost","root","");
mysql_select_db("users");
$query = mysql_query("SELECT * FROM users");
echo "
<table>
<thead>
<th>Username</th>
<th>Password</th>
<th>Email Adress</th>
</thead>";
WHILE($rows = mysql_fetch_array($query)):
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
echo"<tr>
<td>$username</td>
<td>$password</td>
<td>$email</td>
";
endwhile;
?>
答案 2 :(得分:0)
在循环之前打印标题。
<table>
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Email Adress</th>
</tr>
</thead>
<?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 "
<tr>
<td>$username</td>
<td>$password</td>
<td>$email</td>
</tr>
";
endwhile;
?>
</table>
答案 3 :(得分:0)
试试这个:
<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");
?>
<table>
<thead>
<th>Username</th>
<th>Password</th>
<th>Email Adress</th>
</thead>";
<?php
WHILE($rows = mysql_fetch_array($query)):
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
echo "<tr>
<td>$username</td>
<td>$password</td>
<td>$email</td>
";
endwhile;
?>