?
Solved

processing shopping cart order

Posted on 2006-04-04
9
Medium Priority
?
521 Views
Last Modified: 2013-11-29
hi i have a shopping cart which i found on the net and did a few alters to it, the cart is working all fine so far, but what i wanted to know is how do i send the details of the the items in the cart to the checkout.php page if the user decides checkout, just to confirm what they have brought . Thanks

this is the code for my cart.

cart.php

<?php
@session_start();
if(isset($_SESSION['user_name']))

{
}
else
{
 echo "<B>You must login to continue with cart <a href='login.php'>Click Here To Login</a>";
exit;
}

      include("db.php");
            
      switch($_GET["action"])
      {
            case "add_item":
            {
                  AddItem($_GET["id"], $_GET["qty"]);
                  ShowCart();
                  break;
            }
            case "update_item":
            {
                  UpdateItem($_GET["id"], $_GET["qty"]);
                  ShowCart();
                  break;
            }
            case "remove_item":
            {
                  RemoveItem($_GET["id"]);
                  ShowCart();
                  break;
            }
            default:
            {
                  ShowCart();
            }
      }

      function AddItem($itemId, $qty)
      {
            // Will check whether or not this item
            // already exists in the cart table.
            // If it does, the UpdateItem function
            // will be called instead
            
            global $dbServer, $dbUser, $dbPass, $dbName;

            // Get a connection to the database
            $cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
            
            // Check if this item already exists in the users cart table
            $result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");
            $row = mysql_fetch_row($result);
            $numRows = $row[0];
            
            if($numRows == 0)
            {
                  // This item doesn't exist in the users cart,
                  // we will add it with an insert query

                  @mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() . "', $itemId, $qty)");
            }
            else
            {
                  // This item already exists in the users cart,
                  // we will update it instead
                  
                  UpdateItem($itemId, $qty);
            }
      }
      
      function UpdateItem($itemId, $qty)
      {
            // Updates the quantity of an item in the users cart.
            // If the qutnaity is zero, then RemoveItem will be
            // called instead

            global $dbServer, $dbUser, $dbPass, $dbName;

            // Get a connection to the database
            $cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
            
            if($qty == 0)
            {
                  // Remove the item from the users cart
                  RemoveItem($itemId);
            }
            else
            {
                  mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");
            }
      }
      
      function RemoveItem($itemId)
      {
            // Uses an SQL delete statement to remove an item from
            // the users cart

            global $dbServer, $dbUser, $dbPass, $dbName;

            // Get a connection to the database
            $cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
            
            mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");
      }
      
      function ShowCart()
      {
            // Gets each item from the cart table and display them in
            // a tabulated format, as well as a final total for the cart
            
            global $dbServer, $dbUser, $dbPass, $dbName;

            // Get a connection to the database
            $cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
            
            $totalCost = 0;
            $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");
            ?>
            <html>
            <head>
            <title> Your Shopping Cart </title>
            <script language="JavaScript">
            
                  function UpdateQty(item)
                  {
                        itemId = item.name;
                        newQty = item.options[item.selectedIndex].text;
                        
                        document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
                  }
            
            </script>
            </head>
            <body bgcolor="#ffffff">
            <h1>Your Shopping Cart</h1>
            
            
                  <?php
                  
                  while($row = mysql_fetch_array($result))
                  {
                        // Increment the total cost of all items
                        $totalCost += ($row["qty"] * $row["itemPrice"]);
                        ?>
                              
                                                <select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">
                                                <?php
                                                
                                                      for($i = 1; $i <= 20; $i++)
                                                      {
                                                            echo "<option> ";
                                                            if($row["qty"] == $i)
                                                            {
                                                                  echo " SELECTED ";
                                    }
                                                            echo ">" . $i . "</option>";
                                    }
                                    ?>
                              </select>
                                          
                                    
                                    
                              <?php echo $row["itemName"]; ?>
                                          
                                    
                  
<?php echo number_format($row["itemPrice"], 2, ".", ","); ?>
                                          
                                    
                                    
<font face="verdana" size="1" color="black">
<a href="cart.php?action=remove_item&id=<?php echo $row["itemId"]; ?>">Remove</a>
                                          
                                    
                              
<?php
      }
                  
      // Display the total
?>
                              
<a href= "javascript:history.back();" >&lt;&lt; Keep Shopping</a>
                                          

<b>Total: &pound; <?php echo number_format($totalCost, 2, ".", ","); ?></b>
                                          




<form name='form1' method='post' action='checkout.php'>
<?
$cartId=GetCartId();
?>

<input type='hidden' name='cartid' value="<?php echo "$cartId"; ?>">

<input type='submit' name='sub1' value='Check Out'>


</form>
</body>
</html>
<?php
}

?>
0
Comment
Question by:jayjj
  • 5
  • 4
9 Comments
 
LVL 11

Expert Comment

by:Joseph Melnick
ID: 16377438
The table cart has the data stored with the cookieId is field in this table that has the users items.

The function GetCartId() returns the cookieId that you use to lookup all the items in the cart table.

Here is a sample script I wrote for you to output contents of your cart. It uses GetCartId() which I suspect is in the db.php include.

<?php
@session_start();
if(isset($_SESSION['user_name']))

{
}
else
{
 echo "<B>You must login to continue with cart <a href='login.php'>Click Here To Login</a>";
exit;
}

include("db.php");
$dblink = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);

// The following SQL query will get your cart and item info
$query = "select * from cart a ";
$query .= "inner join items b ";
$query .= "on a.itemId = b.itemId ";
$query .= "where a.cookieId = '" . GetCartId() . "' ";
$query .= "order by b.itemName asc"
// get the result
$result = mysql_query($query,$dblink);

$table_rows = '';
$cart_total = 0;
// iterate over the result
while($row=mysql_fetch_array($result)) {
  $itemName = $row['itemName'];
  $itemPrice = $row['itemPrice'];
  $qty          = $row['qty'];
   
  // here you can format the data into table rows until complete
  $table_rows .= '<tr><td>'.$itemName.'</td>';
  $table_rows .= '<td>'.$itemPrice.'</td>';
  $table_rows .= '<td>'.$qty.'</td>';
  $table_rows .= '<td>'.$qty*$itemPrice.'</td></tr>';

  // add everything up
  $cart_total   += $itemPrice * $qty;
}
// assemble rows.

$table_header  = '<table id="checkout">';
$table_header .= '<tr>';
$table_header .= '<th>Name</th>';
$table_header .= '<th>Price</th>';
$table_header .= '<th>Quantity</th>';
$table_header .= '<th>Subtotal</th>'
$table_header .= '</tr>';

$table_footer .= '<tr>';
$table_footer .= '<th>&nbsp;</th>';
$table_footer .= '<th>&nbsp;</th>';
$table_footer .= '<th>TOTAL</th>';
$table_footer .= '<th>'.sprintf("%01.2f",$cart_total).'</th>'
$table_footer .= '</tr>';
$table_footer .= '</table>';

$checkout_table = $table_header . $table_rows  . $table_footer;

// echo as below in your page to display cart items.
echo $checkout_table;

?>

cheers,

Joseph Melnick
0
 

Author Comment

by:jayjj
ID: 16379541
what does the a and the letter b in your query stands for? i have tested your code but it have a problem with this line.

$result = mysql_query($query,$dblink);

$query = "select * from cart a ";
$query .= "inner join items b ";
$query .= "on a.itemId = b.itemId ";
$query .= "where a.cookieId = '" . GetCartId() . "' ";
$query .= "order by b.itemName asc"
0
 

Author Comment

by:jayjj
ID: 16379616
$query .= "order by b.itemName asc" the semicolon ; was missing on this line i think.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:jayjj
ID: 16379690
ok i have tested it, the the heading do appear but the vales for them are empty, the things from the cart does not appear.
0
 

Author Comment

by:jayjj
ID: 16387039
ok ia have sort of edited the code you gave me and came up with something thats working, but its not calculating the items in the cart, its just giveing the price of the last item in the cart. Do you know where i went wrong in the code thanks.

checkout.php code

<?php
@session_start();
if(isset($_SESSION['user_name']))
{

}
            else
      {
             echo "<B>You must login to continue with cart <a href='login.php'>Click Here To Login</a>";
      exit;
      }
include("db.php");
      $dblink = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
      $totalCost = 0;

      //join the item table and cart
      $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");
      $rowcount = mysql_num_rows($result);


?>
      <html>
            <head><title>Checkouts</title></head>
            <body>
            <center>
            <h2>Checkout Items</h2>
<?php
      if ($rowcount <1)       # no rows found
                  {

                        echo "<h3>cart empty</h3>";
                  }
                  else       # at least one row of data returned

                  {
                         echo( "<Table width=300 border=0><TR><TD><h3>Title</h3></TD><TD><h3>Artist</h3></TD><TD><h3>Price</h3></TD><TD><h3>QTY</h3></TD></TR>" );
      //loop through results
      while ($row = mysql_fetch_array($result))
            {
            
                  //create arry of results
                  $itemTitle = $row['itemTitle'];
                  $itemName = $row['itemName'];
                  $itemPrice = $row['itemPrice'];
                  $qty = $row['qty'];
   
                        //print out items in a table
                        echo( "<TR><TD>".$row['itemTitle']."</TD><TD>".$row['itemName']."</TD><TD>".$row['itemPrice']."</TD><TD>".$row['qty']."</TD></TR>" ) ;
            

                              }
                  echo( "</TABLE>" );
                              
                  
                  }


                        // Increment the total cost of all items
                        $totalCost += $itemPrice * $qty ;                              
mysql_free_result($result);
mysql_close($link);
                        
?>

<?php echo number_format($totalCost, 2, ".", ","); ?>
</center>
</body>      
            
</html>            


0
 
LVL 11

Expert Comment

by:Joseph Melnick
ID: 16387852
this line:
  $totalCost += $itemPrice * $qty ;

needs to be inside the while loop after the following lines:

             $itemPrice = $row['itemPrice'];
               $qty = $row['qty'];



totalCost adds up the Total Cost by adding price times quantity an item at a time as it iterates over the result set.

Joseph Melnick
0
 

Author Comment

by:jayjj
ID: 16404995
ok thanks a lot got it working now, but just one more thing, how do i kill my cart session if the user close the site window because each time i close and go back to order, the cart is still their and the session in the cart was not closed.


this is the code i use to create the cart session.

function GetCartId()
      {
            // This function will generate an encrypted string and
            // will set it as a cookie using set_cookie. This will
            // also be used as the cookieId field in the cart table
            
            if(isset($_COOKIE["cartId"]))
            {
                  return $_COOKIE["cartId"];
            }
            else
            {
                  // There is no cookie set. We will set the cookie
                  // and return the value of the users session ID
                  
                  session_start();
                  setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
                  return session_id();
            }
      }


 
0
 
LVL 11

Expert Comment

by:Joseph Melnick
ID: 16409832
unset($_COOKIE["cartId"]); // to unset the cookieId from cookie.

You might want to reduce the length of time that the cookie is set.
AND / OR
remove rows from the cart on order completion that are linked to the cartId. That is after a successful  sale and you redirect them to a thankyou or success page remove the rows.

If there is a timestamp on your cart table you could remove rows that are too old(cleanup / maintenance).




Joseph Melnick

   

0
 
LVL 11

Accepted Solution

by:
Joseph Melnick earned 600 total points
ID: 16409835
You are using a cookie key value pair to refer to rows in your cart table.

Unset Cookie OR reset Cookie cartId to another value on success.
PLUS
Remove old rows.

Joseph Melnick
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month15 days, 18 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question