PHP-生成多个表单,但表单只为每个表单输出相同的内容


PHP - Generating several forms, but the forms only ever output the same thing for each form

好的,所以我基本上已经生成了一个链接列表,这些链接使用表单将变量发送到PHP,这样我就可以从每个链接在下一页上加载不同的东西。然而,每个链接似乎每次都只从数据库请求相同的数据。我使用的PHP版本是5.3.14。

这是第一页的php代码:

    <?php
        //DATABASE CONNECTION
        $News=mysql_query("SELECT * FROM Tutorial");
        while($row=mysql_fetch_array($News))
          {
            printf("<div class='NewsItem'><div class='title'>%s</div><form enctype='multipart/form-data' action='tutorial.php' method='post'><input type='hidden' name='tutorial' value='%s'/><input type='submit' name='submit' value='%s' id='hyperlink-style-button'/></div>", $row['Title'], $row['Title'], $row['Title']);
          }
        ?>

这是第二页的php代码,我希望表单允许我显示每个链接的不同内容

<?php
    //DATABASE CONNECTION
    $Tutorial=$_POST['tutorial'];
    $query="SELECT * FROM Tutorial WHERE Title='$Tutorial'";
    $News=mysql_query($query);
    while($row=mysql_fetch_array($News))
      {
        printf("<div class='NewsItem'><div class='title'>%s</div>%s</div>", $row['Title'], $row['Tutorial']);
      }
     unset($_POST['tutorial']);
     unset($Tutorial);
    ?>

关于如何阻止它无论点击哪个链接都使用相同的数据,有什么想法吗?如果你需要在这里看到代码的作用,还有第一页的链接:网站的例子

您错过了</form>。试试这个。

printf("<div class='NewsItem'><div class='title'>%s</div><form enctype='multipart/form-data' action='tutorial.php' method='post'><input type='hidden' name='tutorial' value='%s'/><input type='submit' name='submit' value='%s' id='hyperlink-style-button'/></form></div>", $row['Title'], $row['Title'], $row['Title'])

我看不到任何其他关键问题,请尝试以下操作。我已经删除了enctype='multipart/form-data',而且在一个页面中有1个以上具有相同id的项目是无效的,所以将id="hyperlink-style-button"更改为class="hyperlink-style-button"。您必须相应地更改css。还将单引号替换为双引号,并为值添加了htmlspecialchars,以避免在引号中打断html。

printf('<div class="NewsItem">
        <div class="title">%s</div>
        <form action="tutorial.php" method="post">
            <input type="hidden" name="tutorial" value="%s"/>
            <input type="submit" name="submit" value="%s" class="hyperlink-style-button"/>
        </form>
        </div>',htmlspecialchars($row['Title']),htmlspecialchars($row['Title']),htmlspecialchars($row['Title']));

也取代

$Tutorial=$_POST['tutorial'];

带有

$Tutorial=mysql_real_escape_string($_POST['tutorial']);

注意:您的代码容易受到SQL注入攻击。请使用事先准备好的报表。

警告:mysql扩展从PHP 5.5.0开始就不推荐使用,将来会被删除。相反,应该使用MySQLi或PDO_MySQL扩展。请不要使用mysql_*来开发新代码。