如何通过单击href删除特定的会话记录



>我无法从会话数组中删除特定记录。我想在单击删除链接时删除表中的特定行。

<?php
session_start();
    if(isset($_GET["product"]) && isset($_GET["category"])){
        $nomProduct = trim($_GET["product"]);
        $category = trim($_GET["category"]);
        $_SESSION['product'][] = array(
            "nomProduct" => $nomProduct ,
            "category" =>  $category
        );
      //session_destroy();
       }
?>
    html table
              <table class="table">
                <?php foreach($_SESSION["product"] as $items) { ?>
                <tr>
                    <th width="250px"><?php echo $items['nomProduct']; ?></th>
                    <td><?php echo $items['category']; ?></td>
                    <td style="text-align: right"><a href="">Delete</a><td>
                </tr>
                <?php }?>
            </table>

'

$key=array_search($_GET['product'],$_SESSION['product']);
if($key!==false)
unset($_SESSION['product'][$key]);
$_SESSION["product"] = array_values($_SESSION["product"]);

'

也许这可能会有所帮助!您需要找到密钥,因为这是一个数组。

编辑:

为您做了一个例子,当您单击链接时,它会从会话数组中删除名字。

<?php
    session_start();
    $_SESSION["user"] = ["fname"=>"William","lname"=>"Henry" ];
    if(isset($_GET["delete"]))
    {
        if($_GET["key"])
        {
            $key=$_GET["key"];
            unset($_SESSION['user'][$key]);
        }
    }
?>

同一页面上的 HTML

<h1>
        <?php 
            if(isset($_SESSION["user"]["fname"]))echo $_SESSION["user"]["fname"]." "; 
            if(isset($_SESSION["user"]["lname"]))echo $_SESSION["user"]["lname"]; 
        ?>
</h1>
    <a href="<?php echo $_SERVER['PHP_SELF']."?delete=user&key=fname" ?>">Delete First Name</a>

如果要删除姓氏(lname(,请在链接的href中更改key=lname,希望此示例对您有所帮助

修改你的HTML

<table class="table">
<?php foreach($_SESSION["product"] as $key => $items) { ?>
  <tr>
    <th width="250px"><?php echo $items['nomProduct']; ?></th>
    <td><?php echo $items['category']; ?></td>
    <td style="text-align: right"><a href=?key="<?php echo $key; ?>">Delete</a><td>
   </tr>
 <?php }?>
</table>

捕获数组密钥并将其从会话数组中删除。

$key = filter_input(INPUT_GET, 'key');
unset($_SESSION['product'][$key]);

最新更新