Tableau 4 colones et suppression de ligne

Résolu
tlaloctzin Messages postés 136 Date d'inscription mercredi 21 juin 2006 Statut Membre Dernière intervention 12 septembre 2013 - Modifié par tlaloctzin le 11/09/2013 à 11:13
tlaloctzin Messages postés 136 Date d'inscription mercredi 21 juin 2006 Statut Membre Dernière intervention 12 septembre 2013 - 12 sept. 2013 à 22:39
Bonjour à tous,
je tente actuellement le dev d un site marchand pour un ami , tout se passe a merveille sauf .... la suppression d'un produit présent dans le panier.

J'ai un tableau a quatre colonnes stocké dans la session ($_SESSION['panier']).

Quand je souhaite supprimer une ligne de ce tableau , soit je perds le tableau complet, soit il me supprime deux produits et la notice me mets 'Undefined index 1'.

Ca fait deux jours que je suis la dessus , j ai essayé pas mal de méthodes ( reconstruction du tableau , unset , array_splice .... je ne trouve pas ou se situe le soucis).

Ca fonctionne avec un ou deux produits mais dès que l on passe les 3 cela ne fonctionne plus, si quelqu'un avait la solution je le bénirait entre tous les saints et je promets de faire une statue à son effigie dès que j ai fini le site !
Merci par avance :)

voici le code , le soucis se trouve dans la fonction dellFromPanier();
<?php
include_once('DataSql.php');

/* 
Structure du panier :
------------------------------------------------------
| IDPRODUIT | PRIXUNITAIRE | QUANTITE | DENOMINATION | 
------------------------------------------------------

*/
//verrification des elements de session liés au panier
if (empty($_SESSION['panier'])){
  $_SESSION['panier'] =array();
}
if (! isset($_SESSION['panier'])){
  $_SESSION['panier'] =array();
}
if (! is_array($_SESSION['panier'])){
  $_SESSION['panier'] =array();
}
class Panier{
 


//comptage des elements du pannier
function getElementCount(){
$count = 0; 

for ( $i = 0 ; $i < sizeof($_SESSION['panier']) ; $i ++){
                 $count+= $_SESSION['panier'][$i][2];
                }

  
return $count;
}
//calcul du prix total sans les frais de ports
function getTotalPrice(){
$price = 0; 
for ( $i = 0 ; $i < sizeof($_SESSION['panier']) ; $i ++){
               $price += $_SESSION['panier'][$i][1]*$_SESSION['panier'][$i][2];
        }
  
return $price;
}
//ajout d'un élément dans le panier
function addToPanier($idProduit,$prix,$quantite,$denomination){
//on commence par vérifier si le produit est présent dans le panier , si c est le cas on ne fait qu en ajouter une unité 
$ispresent = false ; // le boolean de controle de présence dans le panier
for ( $i=0; $i < sizeof($_SESSION['panier']) ; $i++){
    if ($_SESSION['panier'][$i][0] == $idProduit ){
     $ispresent = true;
     $_SESSION['panier'][$i][2] = $_SESSION['panier'][$i][2] +$quantite;
    }
}
if (! $ispresent ){
 
 $taille = sizeof($_SESSION['panier']);
 $_SESSION['panier'][$taille][0] = $idProduit;
 $_SESSION['panier'][$taille][1] = $prix;
 $_SESSION['panier'][$taille][2] = $quantite;
 $_SESSION['panier'][$taille][3] = $denomination;
 
 
}
         
}
//suppression d un element du panier

function dellFromPanier($idproduit){
    $temp = array();
    for ( $i = 0 ; $i < sizeof($_SESSION['panier']) ; $i ++ ){
        if ($_SESSION['panier'][$i][0] != $idproduit){
           
           $temp[$i][0] = $_SESSION['panier'][$i][0];
           $temp[$i][1] = $_SESSION['panier'][$i][1];
           $temp[$i][2] = $_SESSION['panier'][$i][2];
           $temp[$i][3] = $_SESSION['panier'][$i][3];
            
            
        }
    }
    unset($_SESSION['panier']);
    $_SESSION['panier'] = array();
    for ( $i = 0 ; $i < sizeof($temp) ; $i ++ ){ 
    
    $_SESSION['panier'][$i][0] = $temp[$i][0];
    $_SESSION['panier'][$i][1] = $temp[$i][1];
    $_SESSION['panier'][$i][2] = $temp[$i][2];
    $_SESSION['panier'][$i][3] = $temp[$i][3];
    }
}
//modification de la quantité d un produit dans le panier
function updateQuantity($idProduit,$quantity){
  for ( $i=0; $i < sizeof($_SESSION['panier']) ; $i++){
    if ($_SESSION['panier'][$i][0] == $idProduit ){
     $_SESSION['panier'][$i][2] = $quantity;
     
     }
    
       }
}

function getSmallPanier(){
    $nbr  = $this->getElementCount();
    $prix = $this->getTotalPrice();
    $smallListe = '';
    
    if ( $nbr > 0 ){
        $smallListe .= '<center>Votre panier contient <br /><br /><b>';
        $smallListe .= $nbr.' produit(s) <br />';
        $smallListe .= 'Total : '.$prix.' €</b><br /><br />';
        $smallListe .='<div class="button_01"><a href="monpanier.php">Détails</a></div></center>';
        
    }
    else{$smallListe = '<center><i>Votre Panier est vide</i></center>';}
    return $smallListe;
}


function getPanierDetails(){
 $SQL = new DataSql();
        $liste = '';
        $nbr  = $this->getElementCount();
 if ($nbr > 0 ){
             $liste = '<table id="cart"><tr><td colspan="2"><b>Article</b></td><td><b>Prix unitaire</b></td><td colspan="3"><b>Quantité</b></td><td><b>Total TTC </B></td></tr>';

  $totalPrice = 0;
  for ($i =0 ; $i < sizeof($_SESSION['panier']) ; $i ++ ){
     $total = ($_SESSION['panier'][$i][1]*$_SESSION['panier'][$i][2]);
     $totalPrice += $total;
     $nomCommercial = $SQL->getProductName($_SESSION['panier'][$i][0]);
     $liste.='<tr><td>
     <form name="supress" action="removecart.php" method="POST">
     <input type="hidden" name="id" value="'.$_SESSION['panier'][$i][0].'">
     <input border="0" src="images/buttons/trash.png" type="image" value="submit">
     </form>
     </td><td>
     '.$nomCommercial.'</td><td>'.$_SESSION['panier'][$i][1].'</td><td>
     <form name="modif" action="updatePanier.php" method="POST">
     <input type="hidden" name="id" value="'.$_SESSION['panier'][$i][0].'"><input type="hidden" name="base" value="'.$_SESSION['panier'][$i][2].'">
     <input type="hidden" name="act" value="minus">
     <input border="0" src="images/buttons/moins.png" type="image" value="submit">
     </form></td><td>'.$_SESSION['panier'][$i][2].'</td><td>
     <form name="modifplus" action="updatePanier.php" method="POST">
     <input type="hidden" name="id" value="'.$_SESSION['panier'][$i][0].'"><input type="hidden" name="base" value="'.$_SESSION['panier'][$i][2].'">
     <input type="hidden" name="act" value="more">
     <input border="0" src="images/buttons/plus.png" type="image" value="submit">
     </form>
     </td><td>'.$total.'</td></tr>';    
  }
 $liste.='</table><br /> <div id="prixPanier"><table border="0"><tr><td>Total H.T :</td><td>'.round(($totalPrice - round(($totalPrice*0.196),2)),2).'€ </td></tr><tr><td> T.V.A :</td><td> '.round($totalPrice*0.196,2).' €</td></tr><tr><td> <br />Total T.T.C : </td><td><br /><b>'.$totalPrice.' </b> €</td></tr></table></div>'; 
 
        
                }
 else{
  $liste = '<center><i>Votre Panier est vide</i></center>';
  
 }
 



echo $liste;
}
function getFinalPanierDetails(){
 $SQL = new SqlDb();
 $liste = '<table id="cart"><tr><td><b>Article</b></td><td><b>Prix unitaire</b></td><td ><b>Quantité</b></td><td><b>Total TTC </B></td></tr>';
 
  $totalPrice = 0;
  for ($i =0 ; $i < sizeof($_SESSION['panier']) ; $i ++ ){
     $total = ($_SESSION['panier'][$i][1]*$_SESSION['panier'][$i][2]);
     $totalPrice += $total;
     $nomCommercial = $SQL->getProductName($_SESSION['panier'][$i][0]);
     $liste.='<tr><td>
     '.$nomCommercial.'</td><td>'.$_SESSION['panier'][$i][1].'</td><td>'.$_SESSION['panier'][$i][2].'</td><td>'.$total.'</td></tr>';    
  }
 $liste.='</table><br /> <div id="prixPanier2"><table border="0"><tr><td>Total H.T :</td><td>'.round(($totalPrice - round(($totalPrice*0.196),2)),2).'€ </td></tr><tr><td> T.V.A :</td><td> '.round($totalPrice*0.196,2).' €</td></tr><tr><td> <br />Total T.T.C : </td><td><br />'.$totalPrice.'   €</td></tr>
 <tr><td>Frais de ports : </td><td>'.$_SESSION['fdp'].'</td></tr><tr><td>Montant total de la commande : </td><td><font size="4px">'.($totalPrice + $_SESSION['fdp']).' €</font></td></tr></table></div>'; 
 
return $liste;
}
}
?>


Il vaut mieu être riche et en bonne santé que pauvre et malade .

3 réponses

f0xi Messages postés 4205 Date d'inscription samedi 16 octobre 2004 Statut Modérateur Dernière intervention 12 mars 2022 35
Modifié par f0xi le 12/09/2013 à 18:13
La classes Cart et les constantes globales qui vont bien :

<?php
session_start();

define("xCART",   "cart"); // session cart[ product id index ]
define("xID" ,    "id");   // session cart[id][ id index ]
define("xREF" ,   "ref");  // session cart[id][ reference index ]
define("xQTY" ,   "qty");  // session cart[id][ quantity index ]
define("xNAME" ,  "nme");  // session cart[id][ name index ]
define("xPRICE" , "prc");  // session cart[id][ price index ]

if(!isset($_SESSION[xCART]) || !is_array($_SESSION[xCART])){
  $_SESSION[xCART] = array();
}

define("MIN_CART_QTY", 0);
define("MAX_CART_QTY", 9999);
define("TAXE", 19.6);

/* --------------------------------------- */

class Cart{
  /* Add product to cart 
  */
  static public function addProduct($id, $reference, $quantity, $price, $name){
    if(!array_key_exists($id, $_SESSION[xCART])){
      $_SESSION[xCART][$id][xID]    = $id;  
      $_SESSION[xCART][$id][xREF]   = $reference;  
      $_SESSION[xCART][$id][xQTY]   = $quantity;  
      $_SESSION[xCART][$id][xPRICE] = $price;  
      $_SESSION[xCART][$id][xNAME]  = $name;  
    } else {
      self::setQuantity($id, $quantity);
    }
  }
  
  /* delete product from cart (by product id)
  */
  static public function deleteProduct($id){
    if(array_key_exists($id, $_SESSION[xCART])){
      unset($_SESSION[xCART][$id]); 
      return true;
    }
    return false;
  }
  
  /* set in cart product quantity (add or replace) 
     add (old qty + new qty) : self::setQuantity("id", 9)       : qty = old + 9
     replace quantity        : self::setQuantity("id", 9, true) : qty = 9
  */
  static public function setQuantity($id, $quantity, $replace = false){
    if(array_key_exists($id, $_SESSION[xCART])){
      if($replace){
        $_SESSION[xCART][$id][xQTY] = max($quantity, MIN_CART_QTY);
      } else {
        $_SESSION[xCART][$id][xQTY] = min($quantity+$_SESSION[xCART][$id][xQTY], MAX_CART_QTY);
      }
    }
    if($_SESSION[xCART][$id][xQTY] == 0){
      self::deleteProduct($id);
    }
  }
  
  /* get total of a product price in cart (qty * price) 
  */
  static public function getProductTotalPrice($id){
    if(array_key_exists($id, $_SESSION[xCART])){
      return $_SESSION[xCART][$id][xQTY] * $_SESSION[xCART][$id][xPRICE];
    } 
    return 0;
  }
  
  /* get total of ALL products quantities in cart
  */
  static public function getCartTotalQuantity($id){
    $t = 0;
    foreach($_SESSION[xCART] as $k => $product){
      $t += $product[xQTY];
    }
    return $t;
  }
  
  /* get total of ALL products prices in cart
  */
  static public function getCartTotalPrice(){
    $t = 0;
    foreach($_SESSION[xCART] as $k => $product){
      $t += self::getProductTotalPrice($product[xID]);
    }
    return $t;
  }
  
  /* render cart summary (html)
  */
  static public function showCartSummary(){
    /*
      CSS class :
        #cart_summary .empty_cart
        #cart_summary .block
        #cart_summary .product_row
        #cart_summary .product_row dt
        #cart_summary .product_row dt span
        #cart_summary .product_row dt .p_ref
        #cart_summary .product_row dt .p_desc
        #cart_summary .product_row dt .p_price
        #cart_summary .product_row dt span a
        #cart_summary .product_row dt span a:hover
        #cart_summary .product_row dd 
        #cart_summary .product_row dd span
        #cart_summary .product_row dd .p_qty
        #cart_summary .product_row dd .p_total
        #cart_summary .block span 
        #cart_summary .block 
        #cart_summary .block .text
        #cart_summary .block .c_total 
        #cart_summary #cart_summary_btn        
    */
    $tpl = '<div id="cart_summary">';
    if(empty($_SESSION[xCART])){
      $tpl .= '<p class="empty_cart">Votre panier est vide.</p>';
    } else
    {
      foreach($_SESSION[xCART] as $k => $product){
        $tpl .= '<dl class="product_row">'.
                  '<dt>'.
                    '<span class="p_ref">'.$product[xREF].'</span>'.
                    '<span class="p_desc"><a href="link to product" title="'.$product[xNAME].'" target="_blank">'.$product[xNAME].'</a></span>'.
                    '<span class="p_price">'.$product[xPRICE].' €</span>'.
                  '</dt>'.
                  '<dd>'.                  
                    '<span class="p_qty">x '.$product[xQTY].'</span>'.
                    '<span class="p_total"> '.(self::getProductTotalPrice($product[xID])).' €</span>'.
                  '</dd>'.
                '</dl>';
      }
      $tpl .= '<p class="block">'.
                '<span class="text">Total</span>'.
                '<span class="c_total">'.(self::getCartTotalPrice()).'</span>'.
              '</p>'.
              '<p class="block">'.
                '<input id="cart_summary_btn" type="submit" value="Commander">'.
              '</p>';
    }    
    $tpl .= '</div>';
    return $tpl;
  }
  
  /* render cart details (html)
  */
  static public function showCartDetails(){
    /* la flemme */
  }
}
?>



Exemple d'utilisation statique dans un HTML (utilisable également en Ajax bien entendus :
<!DOCTYPE html>
<html>
<head>
<style>
*,html{
  font-family:verdana;
  font-size:10pt;
  padding:0;
  margin:0;
}
#cart_summary,
#cart_summary .block,
#cart_summary .product_row
{
  display:block;
  margin:2px 4px;
  max-width:400px;
}
#cart_summary .product_row:nth-child(even){
  background:#efefef;
}
#cart_summary .product_row:nth-child(odd){
  background:#d0d0d0;
}
#cart_summary .product_row dt,
#cart_summary .product_row dd 
{
  display:inline-block;
}
#cart_summary .product_row dt span,
#cart_summary .product_row dd span
{
  display:inline-block;
  padding:0 4px;
  min-width:40px;
}
#cart_summary .product_row dt .p_ref
{
  text-align:left;
}
#cart_summary .product_row dt .p_desc
{
  text-align:left;
}
#cart_summary .product_row dt .p_price
{
  text-align:right;
}
#cart_summary .product_row dd .p_qty
{
  text-align:left;
}
#cart_summary .block span 
{
  min-width:50px;
}
#cart_summary .block 
{
  text-align:right;
}
#cart_summary .block .text
{
  text-align:right;
  font-weight:bold;
}
#cart_summary .product_row dd .p_total,
#cart_summary .block .c_total 
{
  text-align:right;
  font-weight:bold;
}
</style>
</head>
<body>
<?php
Cart::addProduct('0', 'AB-001', 4, 1.59, 'Test 0');
Cart::addProduct('0', 'AB-001', 1, 1.59, 'Test 0');
Cart::addProduct('1', 'AB-002', 6, 3.20, 'Test 1');
Cart::addProduct('2', 'AB-003', 2, 7.80, 'Test 2');
Cart::addProduct('3', 'AB-004', 1, 15.00, 'Test 3');

echo Cart::showCartSummary();

?>
</body>
</html>


Voila ... y'avait un problème ?

________________________________________________________
[ besoin de câbles audio, vidèo, informatique pas cher ?]
1
f0xi Messages postés 4205 Date d'inscription samedi 16 octobre 2004 Statut Modérateur Dernière intervention 12 mars 2022 35
12 sept. 2013 à 18:32
pour Ajax on peu imagine un communicateur comme celui ci :

/* cart.actions.php */

function getParam($p, $default){ return isset($_GET[$p])?$_GET[$p]:(isset($_POST[$p])?$_POST[$p]:$default)); }

$action = getParam('a', false);

if($action !== false){
  $action = json_decode(base64_decode($action));
  
  switch($action->action){
    case('add'):
      if($action->productDatasSet){
        Cart::addProduct($action->productId, $action->productRef, $action->productQty, $action->productPrice, $action->productName);
      } else {
        Cart::addProduct($action->productId);
      }
    break;
    case('delete'):
      Cart::deleteProduct($action->productId);
    break;
    case('emptyCart'):
      $_SESSION[xCART] = array();
    break;
    case('setQty'):
      echo Cart::setQuantity($action->productId, $action->qty);
    break;
    case('productTotalPrice'):
      echo Cart::productTotalPrice($action->productId);
    break;
    case('productTotalQty'):
      echo Cart::productTotalQty($action->productId);
    break;
    case('cartTotalPrice'):
      echo Cart::cartTotalPrice();
    break;
    case('showCartSummary'):
      echo Cart::showCartSummary();
    break;
    case('showCartDetails'):
      echo Cart::showCartDetails();
    break:
  }
}

/* --------------------------------------- */
0
tlaloctzin Messages postés 136 Date d'inscription mercredi 21 juin 2006 Statut Membre Dernière intervention 12 septembre 2013 3
12 sept. 2013 à 22:39
Merci !
0
cod57 Messages postés 1653 Date d'inscription dimanche 7 septembre 2008 Statut Membre Dernière intervention 11 septembre 2013 19
11 sept. 2013 à 14:36
bonjour
sans rentrer dans tout ton code je ferai
<?php
function dellFromPanier($idproduit){
    
	if(is_array($_SESSION['panier']) && !empty($_SESSION['panier'])){
		foreach($_SESSION['panier'] as $k){
			unset($_SESSION['panier'][$idproduit]);
		}
	}
		
}
?>
0
tlaloctzin Messages postés 136 Date d'inscription mercredi 21 juin 2006 Statut Membre Dernière intervention 12 septembre 2013 3
11 sept. 2013 à 22:50
Bonsoir et merci de ta réponse ,
malheureusement ce que tu me proposes ne fonctionne pas , ca ne supprime d'ailleurs rien dans mon tableau.
0
Rejoignez-nous