一个静态php变量,只分配一次但从未更改过

时间:2014-12-16 19:57:40

标签: javascript php shopping-cart

页面是在线商店页面,用户获得js提示输入购物车的名称,然后选择要添加到购物车的产品,注意每个产品都有自己的形式并且添加到购物车按钮,问题是我希望购物车的名称是静态的。一旦用户输入它,它将被存储为他选择的所有下一个产品,但现在发生的是添加第一个产品工作正常,但第二个产品的购物车名称似乎是空的。

JS CODE:

function myFunction() {
    var person = prompt("Please enter Cart Name");

    document.getElementById("person").value=person;
    document.getElementById("form").submit();

   // if (person != null) {
   //     document.getElementById("demo").innerHTML =
     //   "Your Cart Name is " + person;
    //}


}

PHP:

 <?php 
    //ini_set('display_errors',1); 
    // error_reporting(E_ALL);
    include('connection.php');

                        if ( isset($_POST['Pro_ID'], $_POST['Price'] , $_POST['Pro_Name'] ) ) {

    static $cart=$_POST['cart_Name'];  //this line is just a try, but it gives me an error: Parse error: syntax error, unexpected '$_POST' (T_VARIABLE)

                        $qry="INSERT INTO shopping_cart(Cart_Name,Pro_Name,Pro_ID,Price) VALUES ('$cart','".$_POST['Pro_Name']."',".$_POST['Pro_ID'].",".$_POST['Price'].")";
                            $result = mysql_query ($qry );
    $qry = 'SELECT * FROM product' ;
                        }
                    else

                            $qry = 'SELECT * FROM product' ;
                        //Run QUERY
                        $result = mysql_query ($qry);



      ?> 

对于变量cart_Name,它已作为隐藏输入传递

2 个答案:

答案 0 :(得分:1)

所以基本上你做的是这样的事情:

if(!isset($_SESSION['cart_name']) && isset($_POST['cart_name'])) {
   $_SESSION['cart_name'] = $_POST['cart_name'];
}

// then reference $_SESSION['cart_name'] from there on out.

在尝试与session_start()互动之前,不要忘记在您的网页上致电$_SESSION

现在在JS方面,如果购物车还没有被命名,你只想调用你的提示。所以我要做的就是在页面上输出一个var - 需要在页面上任意调用myFunction()之前输出... id可能会把它放在顶部...:

<script type="text/javascript">
   var cartName = <?php echo isset($_SESSION['cart_name']) 
     ? json_encode($_SESSION['cart_name']) 
     : 'null'; 
   ?>; 
</script>

然后在你的功能中你可以检查它:

function myFunction() {
    // note the lack of `var` - this means we are referencing the global namedCart
    // normally i would recommend passing this in as an argument but i dont have enough detail
    // on your set up
    if (namedCart === null) {
      // if named cart doesnt exist we name it from the prompt
      namedCart = prompt("Please enter Cart Name");
    }

    document.getElementById("person").value=namedCart;
    document.getElementById("form").submit();
}

答案 1 :(得分:0)

请参阅php manuel关于session_start() $ _SESSION [] http://php.net/manual/en/function.session-start.php