无法将多个值添加到$ _SESSION变量中,而不使用键而只使用值

时间:2015-10-11 17:20:42

标签: php ajax session session-variables

我需要通过ajax更新$_SESSION['all_product_ids']所有produkt_id值作为POST变量传递,并将它们保存在此会话变量的数组中。

问题在于,由于某种原因,该值始终被覆盖,并且从未添加到当前值。

我的ajax回调函数中有这段代码:

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

    $product_id = $_POST['product_id'];


    if ( isset ( $_SESSION['all_product_ids'] ) ) {
        // do nothing
    } else {
        $_SESSION['all_product_ids'] = [];
    }


    if ( in_array($product_id, $_SESSION['all_product_ids']) ) {
            // do nothing if product id already in the array
    } else {

        $_SESSION['all_product_ids'][] = $product_id;

    }

    echo json_encode( $_SESSION['all_product_ids'] );

}

问题是ajax总是只返回一个(最后点击/添加的产品ID),因此响应为["78"]["60"],但从不["78", "60"]

我做错了什么?

2 个答案:

答案 0 :(得分:0)

请改为尝试:

<?php
session_start();
if( !empty( $_POST['product_id'] ) ) { 

    $product_id = $_POST['product_id'];

    if ( isset ( $_SESSION['all_product_ids'] ) ) {
        // do nothing
    } else {

        $_SESSION['all_product_ids'][] .= $product_id;
    }


    if ( in_array($product_id, $_SESSION['all_product_ids']) ) {
            // do nothing if product id already in the array
    } else {

        $_SESSION['all_product_ids'][] .= $product_id;

    }

    echo json_encode( $_SESSION['all_product_ids'] );

}

备注:

1 - 您需要在脚本的开头添加session_start(); 2 - 我已将isset更改为!empty,否则您可能会获得空值 3 - 请注意.=将附加到现有数组,而=将替换数组中的任何内容。
4 - 我在服务器上测试了代码,并将值成功附加到$_SESSION['all_product_ids']

答案 1 :(得分:0)

// determine if session has started
Function HasSessionStarted() {

    $result = false;

    // Check if session has started
    IF ((session_status() == PHP_SESSION_NONE) || (session_id() == '')) { 
        $result = true; 
    }

    return $result;

}

Function Upd_Product_Session() {

    $sess_products = array();

    IF ( (isset($_POST['product_id'])) && (!empty($_POST['product_id'])) ) {

        $product_id = $_POST['product_id']; // should really do some sanitization and validation

        $new_session = HasSessionStarted(); // Check Session Status
        IF ($new_session) { session_start(); }

        IF (isset( $_SESSION['all_product_ids'])) {
            $sess_products = json_decode($_SESSION['all_product_ids'], true); // json decode existing session
        }

        IF (!in_array($product_id, $sess_products) ) { // not in array -> add it
            $sess_products[] = $product_id;
        }

        // Set Session
        $_SESSION['all_product_ids'] = json_encode($sess_products);
        IF ($new_session) { session_write_close(); }

    }

    // debugging
    die('<pre>'.print_r($sess_products, true).'</pre>');

}