【问题标题】:Passing ID through href inside while php loop在while php循环中通过href传递ID
【发布时间】:2017-08-27 13:43:59
【问题描述】:

我的这个 while 循环工作正常,除了表中的最后一行我无法让 id 正确通过。 它没有给我任何错误,但是当我将鼠标悬停在“修改”链接上时,它会显示正确的 ID,然后是表格的所有 html 代码。 看起来它没有正确连接。

代码如下:

while ($row = mysqli_fetch_assoc($result)){
    echo "<table><tr><td>" . $row["id"] . "</td>" . 
         "<td>" . $row["product_name"] . "</td>" .
         "<td>" . $row["visible"] . 
         "<td><a href=\"modify.php?id=" . $row["id"] . ">Modify</a>" .
         "</td></tr></table>";
}

【问题讨论】:

  • 你的href 没有关闭
  • 查看 PHP 错误日志以调试错误,并且(并不总是有用但值得绑定)查看源代码以查看 HTML 错误:)

标签: php mysql concatenation


【解决方案1】:

您为每条记录使用echo,这很好,但每次您回显一个全新的表时。您可能的意思是只回显一个新行。正如其他人所建议的那样,您的 href 也没有正确关闭

执行以下操作:

echo '<table>';
while($row = mysqli_fetch_assoc($result)){
  echo "<tr>
          <td> $row[id] </td>
          <td> $row[product_name] </td>
          <td> $row[visible] </td>
          <td><a href='modify.php?id=$row[id]'>Modify</a></td>
        </tr>";
}
echo '</table>';

请注意,因为您正在编写 HTML,所以您不需要连接许多字符串。你可以有一个长的多行字符串。即使您的字符串中有换行符,浏览器也会很好地呈现表格。另外,PHP 可以解析双引号字符串并用变量替换它们的字符串值,所以你不需要做"&lt;td&gt;" . $row["id"];这很好用:"&lt;td&gt;$row[id]"

【讨论】:

  • 非常感谢!!极好的!!它的工作原理!不仅解决了我的问题(找不到结束的href),还让它变得更简单了!!
  • @Willian 很好。如果对你有帮助记得选择我的答案
【解决方案2】:

您似乎错过了" 并且没有关闭您的href。下面我通过添加缺少的" 来修复它。此外,我将大部分双引号换成了单引号。这是我的偏好,因为它更容易阅读;我怀疑由于仅使用双打,您无法识别丢失的报价。

    while ($row = mysqli_fetch_assoc($result)){
        echo '<table><tr><td>' . $row["id"] . '</td>' .
             '<td>' . $row["product_name"] . '</td>' .
             '<td>' . $row["visible"] .
             '<td><a href="modify.php?id=' . $row["id"] . '">Modify</a>' .
             '</td></tr></table>';
    }

【讨论】:

  • 谢谢戴夫!你是对的!双引号太多太乱了!单引号使其可读。
【解决方案3】:

您似乎忘记在您的 while 循环中关闭 href 属性。

此外,正如其他答案所述,每次运行此循环时,您都在使用 echo | print 打印一个新表,这可能会导致一些奇怪的结果。

这是一个示例,您将所有内容附加到字符串名称 $table 并在完成循环后将其打印出来:

<?php
//Create start of table:
$table = '<table><tbody>';

//Fetch rows:
while ($row = mysqli_fetch_assoc($result)) {

    //append to the table:
    $table .= '<tr><td>' . $row['id'] . '</td>' .
            '<td>' . $row['product_name'] . '</td>' .
            '<td>' . $row['visible'] .   //You forgot the " under here
            '<td><a href="modify.php?id=' . $row['id'] . '">Modify</a>' .
            '</td></tr>';
}

//Append end of table:
$table .= '</tbody></table>';

//print table:
print $table;

【讨论】:

  • 感谢克里斯蒂安!一张多行的表,而不是多张表!
猜你喜欢
  • 2013-07-18
  • 1970-01-01
  • 2013-12-26
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 2012-07-31
相关资源
最近更新 更多