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!
hmbargiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hmbargiAuthor Commented:
Great Ray!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.