简体   繁体   中英

PHP MySQL shopping cart trouble

I am having a lot of trouble with a PHP shopping cart. I followed a tutorial on sanwebe.com.

My page shows my products and shows a cart which can be updated perfectly, I then created a final order page for the customer to fill in their delivery details and payment details and I wanted my script to send all this information, as well as the items in the cart to a table in my database.

I am managing to send the details over using a SQL statement but the problem is that when a customer buys product 1 and product 2 it will only send the data for the first product in the cart. So if the person buys 3 product 1's it will send it over fine but when mixing different products it fails.

I think maybe there needs to be some form of loop or something to pass multiple items?

order.php

<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
</head>

<script type="text/javascript">
  $(document).ready(function() {

     $('#orderform').validate();   // Select the form using its idname and apply the validate() function to it.

  }); // end ready()
</script>

<body>
<div id="products-wrapper">
    <h1>Complete Order</h1>
    <div class="order">


    <form id="orderform"action="process_order.php" method="post">
    <h2>Delivery</h2>
    <p><label for="firstname">First Name:</label> <input type="text" name="firstname" class="required"/></p>
    <p><label for="lastname">Last Name:</label> <input type="text" name="lastname" class="required"/></p>
    <p><label for="email">E-mail:</label> <input type="text" name="email" class="required email"/></p>
    <p><label for="address">Address:</label> <input type="text" name="address" class="required" /></p>
    <p><label for="city">City:</label> <input type="text" name="city" class="required" /></p>
    <p><label for="postcode">Post Code:</label> <input type="text" name="postcode" class="required" /></p>
    <p><label for="country">Country:</label> <input type="text" name="country" class="required" /></p>
    <h2>Payment</h2>
    <p><label for="cardnumber">Card Number:</label> <input type="text" name="cardnumber" class="required"/></p>
    <p><label for="expire">Expiration Date:</label> <input type="text" name="expire" class="required digits"/></p>
    <p><label for="scode">Security Code:</label> <input type="text" name="scode" class="required digits"/></p>
    <p class="submit"><input type="submit" value="Submit" /></p>
    </div>


<div class="shopping-cart">
<h2>Your Order</h2>
<?php
    $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    if(isset($_SESSION["products"]))
    {
        $total = 0;
        echo '<ul>';
        $cart_items = 0;
        foreach ($_SESSION["products"] as $cart_itm)
        {
           $product_code = $cart_itm["code"];
           $results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 5");
           $obj = $results->fetch_object();

            echo '<li class="cart-itm">';
            echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
            echo '<div class="p-price">'.$currency.$obj->price.'</div>';
            echo '<div class="product-info">';
            echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
            echo '<div class="p-qty"><strong>Qty : '.$cart_itm["qty"].'</strong></div>';
            echo '<div>'.$obj->product_desc.'</div>';
            echo '</div>';
            echo '</li>';

            $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
            $total = ($total + $subtotal);
            $vat = ($total * '20' / '100');
            $ordertotal = ($total + $vat);

            echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
            echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
            echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
            echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
            echo '<input type="hidden" name="ordertotal['.$cart_items.']" value="'.$ordertotal.'" />';
            $cart_items ++;

        }
        echo '</ul>';
        echo '<span class="check-out-txt">';
        echo '+VAT : '.$currency.$vat.'  ';
        echo '<br>';
        echo '<strong>Total : '.$currency.$ordertotal.'</strong>  ';
        echo '<br>';
        echo '</span>';
        echo '</form>';

    }else{
        echo 'Your Cart is empty';
    }

    ?>
</div>



</body>
</html>

processorder.php

<!-- File:     process_order.php
      Job:     PHP script to handle the information submitted to it by the webpage named testform.html
-->
<?php
session_start();
include_once("config.php");
?>

<html>
 <head> 
    <title>Form processing script</title> 
  </head>

  <body>

    <?php

      // The form contents are held in a special array named $POST.
      // The next statements assign the information held in $POST to PHP variables for processing
      // Delivery
      $firstname = $_POST["firstname"];   
      $lastname = $_POST["lastname"]; 
      $email = $_POST["email"];
      $address = $_POST["address"];   
      $city = $_POST["city"]; 
      $postcode = $_POST["postcode"];
      $country = $_POST["country"];
      $cardnumber = $_POST["cardnumber"];   
      $expire = $_POST["expire"]; 
      $scode = $_POST["scode"];
      // Order
      $product_name = $_POST["item_name"][0];
      $product_code = $_POST["item_code"][0];
      $product_qty = $_POST["item_qty"][0];
      $ordertotal = $_POST["ordertotal"][0];

       // Make a connection to the MySQL database server

       $dbserverIP="localhost";
       $dbusername="root"; // Use your own name
       $dbuserpassword="";  // Use your own password
       $connection = mysql_connect($dbserverIP,$dbusername,$dbuserpassword) or die("Couldn't connect to the dbserver.");

      // Make a connection to the database

       $dbname="ecomm";  // Use your own database name
       $dbselectok = mysql_select_db($dbname,$connection) or die("Couldn't select the remote database.");


       // Issue an SQL INSERT INTO command to the MySQL RDBMS

       $sqlstatement = "INSERT INTO `ecomm`.`order` (`firstname`, `lastname`, `email`, `address`, `city`, `postcode`, `country`, `cardnumber`, `expire`, `scode`, `product_name`, `product_code`, `product_qty`, `ordertotal`) 
       VALUES ('$firstname', '$lastname', '$email', '$address', '$city', '$postcode', '$country', '$cardnumber', '$expire', '$scode', '$product_name', '$product_code', '$product_qty', '$ordertotal')";

       $sql_result = mysql_query($sqlstatement,$connection) or die("Couldn't execute the SQL INSERT statement");

      // Issue an SQL SELECT command to the MySQL RDBMS

       $sqlstatement = "SELECT * FROM `order`"; 
       $sql_result = mysql_query($sqlstatement,$connection) or die("Couldn't execute the SQL SELECT statement");

     //  Process the information retrieved from the database and display to the user's browser

       while ($row = mysql_fetch_array($sql_result)) 
     { 
         $fn = $row["firstname"]; 
         $ln = $row["lastname"]; 
         $em = $row["email"]; 

        echo  "<BR>$fn $ln $em\n"; 
     }

    // Free up any memory holding the database records

     mysql_free_result($sql_result);

   // Close the connection to the database server

   mysql_close($connection);

    ?>

  </body>

</html>

The problem is with this code:

        // Issue an SQL INSERT INTO command to the MySQL RDBMS

   $sqlstatement = "INSERT INTO `ecomm`.`order` (`firstname`, `lastname`, `email`, `address`, `city`, `postcode`, `country`, `cardnumber`, `expire`, `scode`, `product_name`, `product_code`, `product_qty`, `ordertotal`) 
   VALUES ('$firstname', '$lastname', '$email', '$address', '$city', '$postcode', '$country', '$cardnumber', '$expire', '$scode', '$product_name', '$product_code', '$product_qty', '$ordertotal')";

   $sql_result = mysql_query($sqlstatement,$connection) or die("Couldn't execute the SQL INSERT statement");

It will insert one record into the database for one product of a given quantity (so if I order 3 Iron Man T-Shirts, its okay, but if I want a Captain America Polo as well, it ignores it).

To fix this, you would need to loop or call this page multiple times.

The larger issue is that your database has a design problem. I don't think its good to have all the data you have on the order table. The way I would probably design it is to have the order with a unique ID that contains all the customer and payment info (or better, IDs for those values in a customer table and stored payment table), and then have a order details table that has the item, quantity, associated with the unique order ID.

Since you are already passing the array to this page, you could do something like:

  $firstname = mysql_real_escape_string($_POST["firstname"]);   
  $lastname = mysql_real_escape_string($_POST["lastname"]); 
  $email = mysql_real_escape_string($_POST["email"]);
  $address = mysql_real_escape_string($_POST["address"]);   
  $city = mysql_real_escape_string($_POST["city"]); 
  $postcode = mysql_real_escape_string($_POST["postcode"]);
  $country = mysql_real_escape_string($_POST["country"]);
  $cardnumber = mysql_real_escape_string(($_POST["cardnumber"]);   
  $expire = mysql_real_escape_string($_POST["expire"]); 
  $scode = mysql_real_escape_string($_POST["scode"]);

for ($i = 0; $i < sizeof($_POST["item_name"]); $i++){
  $product_name = mysql_real_escape_string($_POST["item_name"][$i]);
  $product_code =mysql_real_escape_string($_POST["item_code"][$i]);
  $product_qty =mysql_real_escape_string($_POST["item_qty"][$i]);
  $ordertotal = mysql_real_escape_string($_POST["ordertotal"][$i]);

   // Make a connection to the MySQL database server

   $dbserverIP="localhost";
   $dbusername="root"; // Use your own name
   $dbuserpassword="";  // Use your own password
   $connection = mysql_connect($dbserverIP,$dbusername,$dbuserpassword) or die("Couldn't connect to the dbserver.");

  // Make a connection to the database

   $dbname="ecomm";  // Use your own database name
   $dbselectok = mysql_select_db($dbname,$connection) or die("Couldn't select the remote database.");


   // Issue an SQL INSERT INTO command to the MySQL RDBMS

   $sqlstatement = "INSERT INTO `ecomm`.`order` (`firstname`, `lastname`, `email`, `address`, `city`, `postcode`, `country`, `cardnumber`, `expire`, `scode`, `product_name`, `product_code`, `product_qty`, `ordertotal`) 
   VALUES ('$firstname', '$lastname', '$email', '$address', '$city', '$postcode', '$country', '$cardnumber', '$expire', '$scode', '$product_name', '$product_code', '$product_qty', '$ordertotal')";

   $sql_result = mysql_query($sqlstatement,$connection) or die("Couldn't execute the SQL INSERT statement");
  }

My PHP is a bit rusty, but that is the basic structure, you will have to debug and tweak it to make sure it works correctly. You will need to insert mysql_real_escape_string() around any variable strings that can be entered by the user to prevent SQL injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM