processing shopping cart order

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
}

?>
jayjjAsked:
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.

Joseph MelnickSenior Software Developer - Pharmacy ApplicationsCommented:
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
jayjjAuthor Commented:
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
jayjjAuthor Commented:
$query .= "order by b.itemName asc" the semicolon ; was missing on this line i think.
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

jayjjAuthor Commented:
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
jayjjAuthor Commented:
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
Joseph MelnickSenior Software Developer - Pharmacy ApplicationsCommented:
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
jayjjAuthor Commented:
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
Joseph MelnickSenior Software Developer - Pharmacy ApplicationsCommented:
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
Joseph MelnickSenior Software Developer - Pharmacy ApplicationsCommented:
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

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
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
E-Commerce

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.