将值添加到会话数组中

时间:2014-02-05 10:55:59

标签: php session-variables

我正在创建购物车应用程序。我有将每个项添加到会话数组中的逻辑,但我不知道如何将值添加到会话数组中。有人能帮助我吗?

4 个答案:

答案 0 :(得分:5)

向会话数组添加值非常简单。

1.将以下行添加到脚本顶部以开始会话。

session_start();

2.使用以下示例将值添加到会话数组。

$_SESSION['variable1'] = "Test1"; 
$_SESSION['variable2'] = "Test2";

3.检索那些会话数组值,如下例所示。

//Prints whole session array by using below line 
print_r($_SESSION); 
//print individual values by using below examples 
echo isset($_SESSION['variable1']) ? $_SESSION['variable1'] : '';
echo isset($_SESSION['variable2']) ? $_SESSION['variable2'] : '';

如果您仍然发现任何问题,请告诉我

答案 1 :(得分:0)

将每个项目添加到数组并将其分配给会话变量,如此

session_start();
$_SESSION['cart'] = array( ... );

所以你可以像这样访问每个项目

$_SESSION['cart'][0]
$_SESSION['cart'][1]
.
.
.

答案 2 :(得分:0)

尝试

session_start();// First of all start session    
$_SESSION['arry_key_may_be_your_name']='My name';// Add values to session array

答案 3 :(得分:0)

将项添加到SESSION中使用以下代码.. PHP SESSION

<h3>PHP SESSION :Store Multiple User Info In PHP SESSION --codenair.com</h3>
<form method="POST">
 <table>
  <tr>
 <td>UserName:</td>
 <td><input type="text" name="name" required/></td>
  </tr>
 <tr>
 <td>Email</td>
 <td><input type="text" name="email" required/></td>
  </tr>
  <tr>
 <td></td>
 <td><input type="submit" name="submit" value="Add User"/></td>
  </tr>
</table>
 </form>
<?php
 session_start(); 
 if(isset($_POST['submit'])){
 $user=array(
'name'=>$_POST['name'], //Username form field name
'email'=>$_POST['email'] //email form field name
);
$_SESSION['student'][]=$user;  
}
if(isset($_GET['remove'])){
unset($_SESSION['student']);
 //Redirecting After Unset SESSION
  header('location:index.php');
  }
 ?>
 <?php if(!empty($_SESSION['student'])){?>
  <table class="table" cellspacing="0" border="1"> 
  <tr>
   <th>Serial</th>
  <th>Name</th>
  <th>Email</th>
   </tr>
 <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {?>
  <tr>
  <td><?php echo $i;?></td>
  <td><?php echo $_SESSION['student'][$i]['name'];?></td>
 <td><?php echo $_SESSION['student'][$i]['email'];?></td>
  </tr>
 <?php }  ?>
 </table>
 <a href="index.php?remove=remove">Empty User</a>
 <?php }else{
  echo "You have no User in SESSION";
 }?>