dtxb75622 2016-08-18 12:05
浏览 43
已采纳

防止将重复的id添加到会话(数组)

I got a session which adds ids to an array, the problem is every id gets added even if the id is already present. How can I prevent duplicate id's from being added to the array?

I figured I need to check for the id using in_array but I don't know exactly how to use it correctly.

I send the id of the product to my quote page using this link:

<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>

Then on that page I use the following code:

if(!isset($_SESSION['product'])){
    $_SESSION['product'] = array();
}

// CHECK FIRST THAT $_GET['product'] IS SET BEFORE ADDING IT TO SESSION
if( isset($_GET['product'])){
    $_SESSION['product'][] = $_GET['product'];
}
$prods  = implode(",", $_SESSION['product']);

And finally load all the products with the ids that are inside the array:

if(count($_SESSION['product'])  != 0){
//  offerte overzicht
$offerte            = "SELECT * FROM `snm_content` WHERE `id` in (".$conn->real_escape_string($prods).")  AND state = 1";
$offertecon         = $conn->query($offerte);
$offertecr          = array();
while ($offertecr[] = $offertecon->fetch_array());
}

But now everytime I reload the page, the id is added again, it's not really bad since the products are only loaded once, but still I would like to fix this, because I think a query checking for tons of duplicate ids is not the best way.

  • 写回答

2条回答 默认 最新

  • doulaopu2343 2016-08-18 12:27
    关注

    Using in_array is simple - you just check if element is in array:

    var_dump(in_array($element, $array));
    

    In your case it is:

    var_dump(in_array($_GET['product'], $_SESSION['product']));
    

    And the check is:

    // i advise you to check product value as `int`.  
    // Because values as `empty string` or `0` or `false` are considered set
    if( 0 < intval($_GET['product']) && !in_array($_GET['product'], $_SESSION['product']) ) {
        $_SESSION['product'][] = $_GET['product'];
    }
    

    But the more clever solution is to use product id as an array key with some fixed value (1 or true for example):

    $_SESSION['product'] = [
        '101' => 1,
        '102' => 1,
        '106' => 1,
    ];
    

    In this case you don't even need to check if your key exists - if it exists it will be overwritten, if not - will be added:

    if( 0 < intval($_GET['product']) ) {
        $_SESSION['product'][ $_GET['product'] ] = 1;
    }
    // but here you need to take array keys instead of values
    $prods  = implode(",", array_keys($_SESSION['product']));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器