I am creating a shopping cart application. I have the logic of adding each item into a session array but i don't know how to add the values into a session array. Could someone help me ?
Its very simple to add values to session array.
1.Add below line to the top of your script to start session.
session_start();
2.Use below examples to add values to session array.
$_SESSION['variable1'] = "Test1";
$_SESSION['variable2'] = "Test2";
3.Retrieve those session array values like below example.
//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'] : '';
Please let me know if you still find any problems
add each item to an array and assign it to session variable like this
session_start();
$_SESSION['cart'] = array( ... );
so you can access each item like this
$_SESSION['cart'][0]
$_SESSION['cart'][1]
.
.
.
Try
session_start();// First of all start session
$_SESSION['arry_key_may_be_your_name']='My name';// Add values to session array
Add Item into SESSION use the below Codes.. 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";
}?>