【问题标题】:Make contents of a <td> into a link when populated from a php sql query?从 php sql 查询填充时,将 <td> 的内容变成链接?
【发布时间】:2015-12-06 02:30:18
【问题描述】:

我正在使用 SQL 查询来填充 HTML 表。查询运行良好,表看起来不错。现在我想让每行第一列的内容成为超链接。最好的方法是什么?我最好的猜测是在下面的 sn-p 中并没有成功。

...

$fields_num = mysqli_num_fields($result);

echo "<thead>";
echo "<tr>";


// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysqli_fetch_field($result);
    echo "<th>{$field->name}</th>";
}
echo "</tr>\n";
echo "</thead>";

// printing table rows  
while($row = mysqli_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell) {
        if($cell[0]) {
            echo "<td><a href="index2.php/$cell"></a></td>";
        }
        else
            echo "<td>$cell</td>";
    }
    echo "</tr>\n";

....

【问题讨论】:

  • 已经关闭了,只是复制粘贴的时候漏掉了。似乎我错过了更多的东西。
  • 不需要\n,如果你正在回显HTML,你没有关闭你的while循环,你为什么在条件中使用$cell[0],而只是简单地调用整个@987654324 @ 在你的回声中?
  • @d_ominic 实际上,最好使用\n。它生成干净的 HTML,而不是全部放在一行中。自己看看,看看 HTML 源代码。
  • @Fred-ii- 我明白了,我已经有一段时间没有使用 PHP 并忘记了。我假设单独的 echo 行将在新行上。
  • @d_ominic 没问题。使用\n 的额外好处是,在查看 HTML 源代码时(它本身就是一个编码工具),也有助于在调试期间查看是否填充了任何内容,以及一大堆其他原因/好处;- ) 欢呼

标签: php html mysql


【解决方案1】:

希望这能解决你的问题。

<?php

$fields_num = mysqli_num_fields($result);

echo '<thead>';
echo '<tr>';

for($i=0; $i < $fields_num; $i++){

    $field = mysqli_fetch_field($result);
    echo '<th>{'.$field->name.'}</th>';
}

echo '</tr>';

echo '</thead>';
echo '<tbody>';

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

    echo '<tr>';
    foreach($row as $cell) {

        if($cell[0]) {
            echo '<td><a href="index2.php/'.$cell[1].'"></a></td>';
        }else{
            echo '<td>'.$cell[1].'</td>';
        }
    }
}

echo '</tr>';
echo '</tbody>';

?>

【讨论】:

  • 不知道您为什么决定删除 OP 的 \n's - 这将在源代码中生成一长串丑陋的 HTML 代码。执行echo "&lt;td&gt;&lt;a href="index2.php/$cell"&gt;&lt;/a&gt;&lt;/td&gt;" . "\n"; 也更好,等等。对于所有其他与表相关的代码行。
  • @Fred-ii- 好吧,我在显示表格时从未使用过它,我想可能是他写错了。谢谢指出,我还是个学习者
  • \n 在查看 HTML 源代码时也有助于调试,并且更容易发现错误。查看源代码本身就是另一个调试工具;-) 没有多少人将其用作工具;我一直有,现在仍然有。有些人认为它是一种“工具”。
【解决方案2】:

您的 while 循环中的 echo 应该使用单独的数组元素,就像您的 if 语句一样。你也在混淆你的回声中的引号。此外,您应该能够直接将 PHP 变量放入 echos 中,否则与 . 连接

if ($cell[0]) {
    echo "<td><a href='index2.php/$cell[0]'></a></td>";
} else {
    echo "<td>$cell[0]</td>";
}

与 concat 相呼应:

echo "<td><a href='index2.php/".$cell[0]."'></a></td>";

不确定是否可以内联 echo 数组,所以最好只与 . 连接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多