0

我显示数据库中有关产品信息(例如名称和价格)的多行数据,并且还<input type="hidden">与存储在数据库中的每个产品 ID 的值相呼应。我回显这个隐藏的 ID 值,因为我需要跟踪每个产品 ID,因为我希望能够在显示后更新信息。

但是,每当我按下每个产品附近的更新按钮时,表单都会发送 SQL 表中的最后一个产品 ID

这就是我将数据库中的数据显示到 HTML 页面中的方式:

<?php
$products = getAllProducts();
foreach ($products as $product) {
    echo
    '<input type="hidden" name="product_id" value="' . $row['product_id'] .'">                                           
    <tr> 
    <td scope="row">' . $row['name'] . '</td>                                                                    
    <td><input type="text" name="price" value="' . $row['price'] . '"></td>
    <td><input type="submit" name="update" value="Update"></td>    
    <td><input type="submit" name="delete" value="Delete"></td>  
    </tr>';
}
?>     

以及文件中负责更新的一些代码:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $product_id = trim(filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT));
    //$product_id always gets the latest ID in the SQL table instead of the 
    //product ID where the button was clicked in the table row    

    if (isset($_POST['update_button'])) {
    
     

    } else if (isset($_POST['delete_button'])) {

        }
    }
}
4

0 回答 0