首页 > 解决方案 > php 变量(在 HTML 表单操作标记内)不会在 while 循环内递增,尽管在表单外递增

问题描述

我正在生成一个显示数据库值的表。当显示每条记录的值时,我试图通过 URL 发送到下一页的名称字段没有增加,只是保持初始值设置为名称。我看不到这个问题,因为 $name 变量在表单外部递增时不会产生任何问题,但在表单内部却不能递增。

<?php
require_once "config.php";
$sql = "SELECT * FROM restaurant";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    echo "<table><tr><th>Name</th><th>City</th><th>Link</th></tr>";
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row["Name"];
        //$link = "<a href='info.php' >$name</a>";
        echo "<tr><td>" . $name . "</td><td>" . $row["City"] . "</td><td><form action='info.php?name=$name' method='post'><input type='submit' value='reserve now'></td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

mysqli_close($conn);
    

标签: phphtml

解决方案


您将任意文本粘贴到 URL 中,然后将其作为任意文本粘贴到 HTML 中。说白了就是自找麻烦。

首先,将参数正确粘贴到 URL:

$name = $row["Name"];
$action = 'info.php?name=' . urlencode($name); // This will represent special URL characters properly

然后,将其正确粘贴到 HTML

$actionHtml = htmlentities($action); // This will represent HTML characters properly
$form = "<form action='$actionHtml' method='POST'><input type='submit' value='reserve now'/>"

PS:我注意到你忘了关</form>在桌子上;)


推荐阅读