从数据库以有组织的方式显示数据

时间:2013-08-14 20:02:51

标签: php database formatting

我有以下代码

<?php

$connect=mysql_connect("localhost","root","");
mysql_select_db("dbms_teacher",$connect);
$result=mysql_query("SELECT * FROM staffs");
while ($row=mysql_fetch_array($result))
{
echo "<tr>";
    echo "<td>" . $row['fname'] . "</td>";
    echo "<td>" . $row['lname'] . "</td>";
    echo "<td>" .$row['post']. "</td>";
    echo "<td>". $row['status']. "</td>";

    // echo "<td>". "edit/delete". "</td>";
}
mysql_close($connect);

?>

这是从dbms_teacher调出数据的代码部分。有没有办法让我能够以表格形式获取数据,包括名称,帖子,状态,删除选项(我以后可以管理)?我只是需要一种很好的方式以有条理的格式显示它!

3 个答案:

答案 0 :(得分:2)

由于您只使用选择列,因此您可以对其进行硬编码。如果您只获得查询中的那些列,它也会有所帮助:

$result=mysql_query("SELECT fname,lname,post,status FROM staffs");
echo "<table>";
echo "<tr><td>First Name</td><td>Last Name</td><td>Post</td><td>Status</td><td>Edit/Delete</td></tr>";
while ($row=mysql_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['fname'] . "</td>";
    echo "<td>" . $row['lname'] . "</td>";
    echo "<td>" .$row['post']. "</td>";
    echo "<td>". $row['status']. "</td>";
    echo "<td></td>";
    // echo "<td>". "edit/delete". "</td>";
    echo "</tr>";
}
mysql_close($connect);
echo "</table>";
?>

答案 1 :(得分:1)

您必须在循环之前放置echo "<table>";并在循环之后放置echo "</table>";

编辑: 向表中添加一些边框,并在循环之前列出列名:

echo "<table border=1>";
echo "<tr>";
echo "<td><b>fname</b></td><td><b>lname</b></td><td><b>post</b></td><td><b>status</b></td>";
echo "</tr>";

答案 2 :(得分:0)

你需要像这样包含表结构的标记:看到while循环的标记:

<?php

$connect=mysql_connect("localhost","root","");
mysql_select_db("dbms_teacher",$connect);
$result=mysql_query("SELECT * FROM staffs");
echo "<table>";
while ($row=mysql_fetch_array($result))
{
echo "<tr>";
    echo "<td>" . $row['fname'] . "</td>";
    echo "<td>" . $row['lname'] . "</td>";
    echo "<td>" .$row['post']. "</td>";
    echo "<td>". $row['status']. "</td>";

    // echo "<td>". "edit/delete". "</td>";
}
echo "</table>";
mysql_close($connect);

?>