image


Valora:  4.33/5
Inicio » PHP » PHP Tutorial » Sessions




Shopping cart

By: Jose Valle

If after all the abovementioned, you still do not understand what sessions are for, we will have a practical example. Imagine that you are trying to create a shopping cart system , which in its basic form could be something like this:

<?php // Manual de PHP de WebEstilo.com
session_start();
session_register('itemsEnCesta');
$item=$_POST['item'];
$cantidad=$_POST['cantidad'];
$itemsEnCesta=$_SESSION['itemsEnCesta'];

if ($item){
   if (!isset($itemsEnCesta)){
      $itemsEnCesta[$item]=$cantidad;
   }else{
      foreach($itemsEnCesta as $k => $v){
         if ($item==$k){
         $itemsEnCesta[$k]+=$cantidad;
         $encontrado=1;
         }
      }
      if (!$encontrado) $itemsEnCesta[$item]=$cantidad;
   }
}
$_SESSION['itemsEnCesta']=$itemsEnCesta;
?>

<html>
<body>
<tt>
<form action="<?=$PHP_SELF."?".$SID?>" method="post">
Dime el producto <input type="text" name="item" size="20"><br>
Cuantas unidades <input type="text" name="cantidad" size="20"><br>
<input type="submit" value="Añadir a la cesta"><br>
</form>
<?
if (isset($itemsEnCesta)){
   echo'El contenido de la cesta de la compra es:<br>';
   foreach($itemsEnCesta as $k => $v){
      echo 'Artículo: '.$k.' ud: '.$v.'<br>';
   }
}
?>

</tt>
</body>
</html>


Execute View code

A brief explanation: on row 4 we verify whether the user has inserted any item from the form. If the array itemsInCart does not exist on line 5, we create it with the new product and the indicated amount. If the array exists, move along its content between lines 8 and 13, therefore if we find a similar product, we will add the new product and corresponding amount to itemsInCart on row 14.

Next, we print the form and results, if any, starting on line 18, where HTML begins.

Could you imagine the possibilities of an information storing system with these characteristics? No need for files, or databases, or having to move values from one page to another. PHP is managing this data for us, until the moment we decide to store information that is important to us.

These are the basic functions of sessions, I hope this may be useful and do not forget to consult the rest of the statements associated with the use of sessions in the PHP manual.




WebEstilo.com - Introduzca su e-mail y conozca las novedades. No hacemos Spam.
Google
  Web WebEstilo.com   
 
Valid HTML 4.01!
Última modificación:25 de Diciembre de 2004. Spain - España.
© 1998-2004 por Joaquin Gracia. Todos los derechos reservados.