• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 341
  • Last Modified:

Save items for the previous session!

Hi experts,

I'm doing a shopping cart coding using php and I'm stuck in how to save items in the shopping cart. For example, a user logged in and saved items in the shopping cart. Then, he decided to buy the items later so he logged out. When he logged in again, he should view what what items he has chosen from the pervious session in the shopping cart. I already created a session table in the database but don't know how to implement that in php.

Thanks!
0
hmbargi
Asked:
hmbargi
  • 5
  • 5
  • 2
  • +1
1 Solution
 
Hugh McCurdyCommented:
The best way to do this (IMHO) is to save the shopping cart in a database such as mySQL.
0
 
hmbargiAuthor Commented:
I already know that I have to save the items related to each user in the DB before the user logged out. But the big question: how to implement it. Could you please provide an example code that do that.
0
 
Hugh McCurdyCommented:
I didn't know that you already know.  You might be surprised at the number of people who are trying to keep the shopping cart in $_SESSION variables.

Unfortunately, I don't have sample shopping cart code.  Perhaps some other expert has such code in "inventory."


How about we do this?

Let's see if someone shows up with some sample code.  If you get tired of waiting, I can talk to you about design concepts.  (For starters, you'll need a list of the information you want to store such as part #, desc, quan, price.)  I will not have much, if any, time on Saturday to engage in discussions.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
CKY092Commented:
Which portion are you needing code for? The connection between your PHP cart and your MySQL database?

Can you upload some sample code for your PHP cart?
0
 
Hugh McCurdyCommented:
That's well put CKY092.  I think we need some more context.  What information do you plan to store?
0
 
hmbargiAuthor Commented:
Here is the show_cart.php code:

<?php
  include ('hbargi_fns.php');
  // The shopping cart needs sessions, so start one
  session_start();

  @$new = $_GET['new'];

  if($new) {
    //new item selected
    if(!isset($_SESSION['cart'])) {
      $_SESSION['cart'] = array();
      $_SESSION['items'] = 0;
      $_SESSION['total_price'] ='0.00';
    }

    if(isset($_SESSION['cart'][$new])) {
      $_SESSION['cart'][$new]++;
    } else {
      $_SESSION['cart'][$new] = 1;
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
  }

  if(isset($_POST['save'])) {
    foreach ($_SESSION['cart'] as $itemid => $qty) {
      if($_POST[$itemid] == '0') {
        unset($_SESSION['cart'][$itemid]);
      } else {
        $_SESSION['cart'][$itemid] = $_POST[$itemid];
      }
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
  }
 // Delete from cart...
  if($_GET['action'] == 'deletefromcart') {
     deletefromcart($_SESSION['cart'], $_GET['id']);
        
}

  do_html_header("Your shopping cart");
  

  if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
    display_cart($_SESSION['cart']);
  } else {
    echo "<p>There are no items in your cart</p><hr/>";
  }
  
   // get the item info out from
  
  $target = "index.php";

  // if we have just added an item to the cart, continue shopping in that country
  if($new)   {
    $details =  get_item_details($new);
    if($details['catid']) {
      $target = "show_cat.php?catid=".$details['catid'];
    }
  }  
 
  
function deletefromcart($cart, $itemid) {
  //unset ($cart[$itemid]);
    
 unset($_SESSION['cart'][$itemid]);
 $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
 $_SESSION['items'] = calculate_items($_SESSION['cart']);
  header("Location:show_cart.php");
 
  
}
  
  display_button($target, "continue-shopping", "Continue Shopping");

  // use this if SSL is set up
  // $path = $_SERVER['PHP_SELF'];
  // $server = $_SERVER['SERVER_NAME'];
  // $path = str_replace('show_cart.php', '', $path);
  // display_button("https://".$server.$path."checkout.php",
  //                 "go-to-checkout", "Go To Checkout");

  // if no SSL use below code
  display_button("checkout.php", "go-to-checkout", "Go To Checkout");

  do_html_footer();
?>

Open in new window


And this is display_cart function:
function display_cart($cart, $change = true, $images = 1) {
  // display items in shopping cart
  // optionally allow changes (true or false)
  // optionally include images (1 - yes, 0 - no)

   echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\">
         <form action=\"show_cart.php\" method=\"post\">
         <tr><th colspan=\"".(1 + $images)."\" bgcolor=\"#cccccc\">Item</th>
         <th bgcolor=\"#cccccc\">Price</th>
         <th bgcolor=\"#cccccc\">Quantity</th>
         <th bgcolor=\"#cccccc\">Total</th>
         <th bgcolor=\"#cccccc\">Remove</th>
         </tr>";

  //display each item as a table row
  foreach ($cart as $itemid => $qty)  {
    $item = get_item_details($itemid);
    echo "<tr>";
    if($images == true) {
      echo "<td align=\"left\">";
      if (file_exists("images/".$itemid.".jpg")) {
         $size = GetImageSize("images/".$itemid.".jpg");
         if(($size[0] > 0) && ($size[1] > 0)) {
           echo "<img src=\"images/".$itemid.".jpg\"
                  style=\"border: 1px solid black\"
                  width=\"".($size[0]/3)."\"
                  height=\"".($size[1]/3)."\"/>";
         }
      } else {
         echo "&nbsp;";
      }
      echo "</td>";
    }
    echo "<td align=\"left\">
          <a href=\"show_item.php?itemid=".$itemid."\">".$item['name']."</a>
          </td>
          <td align=\"center\">\$".number_format($item['price'], 2)."</td>
                          

          <td align=\"center\">";

    // if we allow changes, quantities are in text boxes
    if ($change == true) {
      echo "<input type=\"text\" name=\"".$itemid."\" value=\"".$qty."\" size=\"3\">";
    } else {
      echo $qty;
    }
    echo "</td><td align=\"center\">\$".number_format($item['price']*$qty,2)."</td>
        
        
         <td align=\"center\"> <a href=\"show_cart.php?action=deletefromcart&id=".$itemid."\">Delete from cart</a>
         
        </td>
            </tr>\n";
  }
  
  // display total row
  echo "<tr>
        <th colspan=\"".(2+$images)."\" bgcolor=\"#cccccc\">&nbsp;</td>
        <th align=\"center\" bgcolor=\"#cccccc\">".$_SESSION['items']."</th>
        <th align=\"center\" bgcolor=\"#cccccc\">
            \$".number_format($_SESSION['total_price'], 2)."
        </th>
        <th align=\"center\" bgcolor=\"#cccccc\"></th>
        </tr>";

  // display save change button
  if($change == true) {
    echo "<tr>
          <td colspan=\"".(2+$images)."\">&nbsp;</td>
          <td align=\"center\">&nbsp&nbsp&nbsp;
             <input type=\"hidden\" name=\"save\" value=\"true\"/>
             <input type=\"image\" src=\"images/save-changes.gif\"
                    border=\"0\" alt=\"Save Changes\"/>
          </td>
          <td>&nbsp;</td>
          </tr>
          <tr></tr>";
  }
  echo "</form></table>";
}

Open in new window

0
 
CKY092Commented:
Do you already have your MySQL database and table set up? If so, what fields are in the table?
0
 
hmbargiAuthor Commented:
I have two tables that deal with sessions.

php_session:

session_id, date_created, last_updated.

session_item:

session_id, customerid, itemid
0
 
Hugh McCurdyCommented:
How are you planning to store multiple items?  (Item ID could be an array)
0
 
hmbargiAuthor Commented:
Each user can have many items in his cart. If he logged out and logged in again, the items he picked from the previous session will show up.
0
 
Hugh McCurdyCommented:
You should be able to store an array.  I haven't done that myself (that I recall).  

What do you need help with next?  Saving to mySQL?  Do you have the table definition done?  (Something you can copy/paste?)
0
 
Ray PaseurCommented:
You can use serialize() to create a string representation of an array, then you can store the array in the data base table.  But I would not do that; instead I would use a normalized representation of the data.
http://lmgtfy.com/?q=Should+I+Normalize+My+Database

But that aside, building your own shopping cart is like building your own car.  Most of us would choose one that already exists and works correctly.  You might find good solutions using Magento, or opening a shop on eBay.  But building your own cart has not really been needed since about 2002.
0
 
hmbargiAuthor Commented:
Great Ray!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 5
  • 5
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now