将sql查询输出到html表中

时间:2015-07-31 03:49:18

标签: php html mysql

我试图将此PHP SQL查询的输出放入数据库表中,但它将所有行数据输出到一列中。

if(isset($_POST['submit'])) {
    $name = htmlentities($_POST['name']);
    $parts = explode(" ", $name);
    $lastname = array_pop($parts);
    $firstname = implode(" ", $parts);

    $connection = mysql_connect("localhost", "user", "password");

    mysql_select_db("shoretoshore", $connection);

    $result = mysql_query("SELECT ship_no, shipment_id, arrival_date, origin,      destination, lname, fname from shipment, captain WHERE captain.capt_id=shipment.capt_id AND captain.fname='$firstname' AND captain.lname='$lastname'", $connection);

    echo '<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
            <tr bgcolor="#FFFFFF" style="font-weight:bold">
            <th>Shipment No.</th>
            <th>Shipment Id.</th>
            <th>Arrival Date</th>
            <th>Origin</th>
            <th>Destination</th>
            <th>Last Name</th>
            <th>First Name</th>
            </tr>';
    while ($row = mysql_fetch_row($result)) {
        foreach ($row as $value)
            print "<tr><td>"."{$value}"."</td></tr>";
        echo "<br>";
    }
    echo "</table>";
}

如何将查询结果输出到HTML表格中?

5 个答案:

答案 0 :(得分:0)

您需要解释您遇到的问题。但是从我可以看到的内容来看,你循环遍历行的所有值并将它们作为行本身输出,而不是作为表行中的单元格输出。围绕值的大括号也是不必要的,因为你连接字符串,你可以只做'<tr><td>'.$value.'</td></tr>' OR "<tr><td>$value</td></tr>"。如果字符串是双引号,PHP将解析字符串中的变量。我也不会将<br>标记添加为表的直接子项。如果表行之间需要间距,请使用填充和边距。

答案 1 :(得分:0)

您将$value放在引号内,它将被视为字符串。

尝试:

while ($row = mysql_fetch_row($result)) {
    echo '<tr>';
    foreach ($row as $value)
    {
      echo "<td>".$value."</td>";
    }
    echo "</tr>";
}

答案 2 :(得分:0)

试试这个

while ($row = mysql_fetch_row($result)) {

    print "<tr><td>".$row[0]."</td></tr>";
    echo "<br>";
}

答案 3 :(得分:0)

问题是您要为每行列输出<tr>标记。您需要将<tr>移到内循环之外。

从技术上讲,您不需要将"{$value}"与其他两个字符串连接起来,但是您确实应该通过$value通过htmlspecialchars()以避免在值包含任何{时产生错误的HTML {1}}或<个字符。例如:

&

此外,您不应该在表行之间使用while ($row = mysql_fetch_row($result)) { print '<tr>'; foreach ($row as $value) { $v = htmlspecialchars ($value); print "<td>$v</td>"; } echo "</tr>\n"; } 元素,这就是我用上面的换行符替换它的原因。就个人而言,我会跳过结束<br></td>标记,因为它们在HTML中是可选的。

另请注意,MySQL扩展已弃用且不再维护。这些天你应该使用MySQLiPDO

答案 4 :(得分:0)

while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value)
{
  echo "<td>".$value."</td>";
}
echo "</tr>";
}