doutang7414 2016-07-26 11:52 采纳率: 0%
浏览 65

从PHP会话中删除一个变量

I Would like to remove a variable from a PHP session array when the user chooses 'Remove'.

But when I unset, ALL the variables in the array are deleted.

How I can delete just one variable?

    <?php

session_start();

if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
    $_SESSION['products'] = [];
}

$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';

if(isset($_GET['delparam'])){
   unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
    $_SESSION['products'][$productName] = $productName;
}
?>

  <?php foreach ($_SESSION['products'] as $product): ?>
    <div class="echo-product"><?php echo htmlspecialchars($product); ?>
     <button type="submit" class="delete-product" value="Remove" >[x]</button>
    </div>
  <?php endforeach;?>

My code is a bit different from the other posts I found on this site. But I really need help with this code...

Update

$('.add-product').click(function() {
    var productName = $(this).data('product');
        $.post('http://examp.nl/reload.php?addparam', {productName: productName}, function(data) {
            $('.echo').html(data);
    })
});

$('.delete-product').click(function() {
    var productName = $(this).data('product');
        $.post('http://examp.nl/reload.php?delparam', {productName: productName}, function(data) {
            $('.echo').html(data);
    })
});

Update If I use the following dump var_dump((unset) $productName); var_dump($productName);

I get this output. Maybe it is of help... NULL string(6) "Item Z"

  • 写回答

2条回答 默认 最新

  • douji5746 2016-07-26 12:32
    关注

    An altenative would be to define a boolean 'productOption' variable, 0 = remove and 1 = add, then your .delete-product would look lie this:

    $('.delete-product').click(function() {
    var productName = $(this).data('product');
    var option = 0; 
        $.post('http://examp.nl/reload.php?delparam', {productName: productName, productOption: option}, function(data) {
            $('.echo').html(data);
    })
    

    Then inside your reload.php script, you verify if the variable isset and then unset the specific session variable you are after.

    I've not tried this code yet but please try it and let me know if it works;

    EDIT

    if you have defined a $_session['product'] variable, then it will hold all the products listed. Think of it as a multidimensional array.

    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持