输出sql查询到html表


Output sql query into html table

我试图将这个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表中?

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

试题:

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

你需要解释你遇到的问题。但从我现在看到的,你在循环遍历行中的所有值并将它们作为行本身输出,而不是作为表格行中的单元格输出。value周围的花括号也是不必要的,因为您正在连接字符串,您可以只执行'<tr><td>'.$value.'</td></tr>'"<tr><td>$value</td></tr>"。如果字符串是双引号,PHP将解析字符串中的变量。我还避免将<br>标记添加为表的直接子标记。

try this

while ($row = mysql_fetch_row($result)) {
    print "<tr><td>".$row[0]."</td></tr>";
    echo "<br>";
}

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

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

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

此外,您不应该在表行之间有<br>元素,这就是我在上面用换行符替换它的原因。就我个人而言,我会跳过结束的</td></tr>标签,因为它们在HTML中是可选的。

还请注意,MySQL扩展已被弃用并且不再维护。这些天你应该使用mysql或PDO

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