目标单个表单 Instance/Counter 在 A PHP While 循环中

Target Individual Form Instance/Counter Inside A PHP While Loop

我有一个 PDO 准备好的语句,我在单个图像页面上使用该语句,用户将能够在该页面上下载该特定图像。我目前有一个计数器,每次单击下载按钮时它都会递增,这会更新 MySQL 数据库中的计数器值。我想将下载计数器从单张图片页面转移到显示多张图片的索引页面上。

因为当您单击下载按钮时 form 元素位于 while 循环内,当前功能会更新此页面上所有图像的计数器(即循环内的所有内容) .

显然我不认为我可以将它移出循环,因为它根本不会更新任何东西?

如何获得它以便在单击表单特定实例的下载按钮时,它只更新特定表单元素的详细信息?

PHP

<?php

    // get username from URL parameter
    isset($_GET['username']) ? $username = $_GET['username'] : header("Location: index.php");

    // fetch filename details from database
    $stmt = $connection->prepare("SELECT * FROM imageposts WHERE username = :username");
    $stmt->execute([':username' => $username]); 

    while ($row = $stmt->fetch()) {

        $db_image_filename = htmlspecialchars($row['filename']);

        // -- HTML that shows the image file goes here --

        // update counter for number of downloads of an image
        if (isset($_POST['download'])) {
            try {
                $sql = "UPDATE imageposts SET downloads = downloads +1 WHERE filename = :filename";
                $stmt = $connection->prepare($sql);

                $stmt->execute([
                    ':filename' => $db_image_filename
                ]);

            } catch (PDOException $e) {
                echo "Error: " . $e->getMessage();
            }
        }
?>

// download button that updates the counter
<form method="post">
    <button type="submit" name="download">Download</button>
</form>

<?php } ?>

解决此问题的一种方法是在循环外添加一些 PHP,它引用循环内隐藏的 <form> 元素的值 - 在这种情况下,您有一个 $db_image_filename 您可以使用的值。

<form method="post">
    <button type="submit" name="download">Download</button>
    <input type="hidden" name="hidden-filename" value="<?php echo $db_image_filename; ?>">
</form>

然后在PHP中引用这个值:

<?php
if (isset($_POST['download'])) {

      // value from hidden form element
      $hidden_filename = $_POST['hidden-filename'];

      try {
           $sql = "UPDATE imageposts SET downloads = downloads +1 WHERE filename = :filename";
           $stmt = $connection->prepare($sql);

           $stmt->execute([
                ':filename' => $hidden_filename
           ]);
           
           header("location: " . $_SERVER['PHP_SELF']);

      } catch (PDOException $e) {
           echo "Error: " . $e->getMessage();
      }
}
?>