Shopping Cart

Now we will be building a simplified Shopping Cart module which will take advantage of our newly built database abstraction class.

Let's map out the features of the Shopping Cart:

  • Shopping List page:
    • The shopper should see several items with their names and prices
    • The shopper should be able to click on a checkbox beside each item which adds it to the cart

  • Checkout page:
    • List of items and their prices
    • Total

  • Confirmation page:
    • Input the details such as the bill-to address, bill-to credit card number, and, of course, the name
    • The shopper should also be able to specify which address to send the goods to

Building the shopping items list

In this page, we will create basic HTML blocks to show the list of items that a shopper may wish to buy.

We will use the same template system which we had earlier, but instead of having the entire code in one page, we'll separate out the header and the footer and simply include them in our files using include(). We'll also use the same Bootstrap framework to make our frontend look nice.

Item template rendering function

We'll be creating the item render function which will render all our shopping items in div. The function will simply return the HTML markup of an item with the price, name, and picture image of the item:

//accepts the database results as an array and calls db functions render_shopping_items($items) 
{ 
$db->iterate_over("<td>", "</td>", $item_name); 
    foreach($items as $item) { 
     $item->name.  ' ' .$item->price . ' ' . $item->pic; 
 
   } 
$resultTable .= "</table>"; 
} 

In the preceding code, we used our freshly created iterate_over function, which formats each value of the database. The end result is we have a table of the items we want to buy.

Let's create a simple layout structure which simply gets the header and footer in each page we build, and from now on, simply includes them:

In header.php:

<html> 
<!doctype html> 
<head> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
</head> 
<body> 

In footer.php:

<div class="footer">Copyright 2016</div></body> 
</html> 

In index.php:

<?php 
require('header.php'); 
//render item_list code goes here 
require('itemslist.php'); //to be coded  
require('footer.php'); 
?> 

Now let's create the itemslist.php page which will be included in the index.php:

<?php  
include('DB.php'); 
$db = new DB(); 
$table = 'shopping_items'; 
$results = $db->select_all($table); 
//calling the render function created earlier: 
foreach(as $item) { 
  echo render_shopping_items($results);  
} 
 
?> 
//shopping items list goes here. 

Our functions are ready but our database does not exist yet. We also need to populate our database.

Let's create some shopping items by creating the shopping_items table in our MySQL database:

CREATE TABLE shopping_items ( 
    id INT(11) NOT NULL AUTO_INCREMENT, 
    name VARCHAR(255) NOT NULL, 
    price DECIMAL(6,2) NOT NULL, 
   image VARCHAR(255) NOT NULL, 
PRIMARY KEY  (id)  
); 

Let's run MySQL and insert the following items into our database:

INSERT INTO `shopping_items` VALUES (NULL,'Tablet', '199.99', 'tablet.png'); 
INSERT INTO `shopping_items` VALUES (NULL, 'Cellphone', '199.99', 'cellphone.png'); 
INSERT INTO `shopping_items` (NULL,'Laptop', '599.99', 'Laptop.png'); 
INSERT INTO `shopping_items` (NULL,'Cable', '14.99', 'Cable.png'); 
INSERT INTO `shopping_items` (NULL, 'Watch', '100.99', 'Watch.png'); 

Let's save it in a file insert_shopping_items.sql. Then, in the same directory as the insert_shopping_items.sql file:

  1. Log on to MySQL client and follow the procedure:
    mysql -u root -p
    
  2. Then type use <name of database>:
    mysql>  use <database>;
    
  3. Import the script by using the source command:
    mysql> source insert_shopping_items.sql
    

When we run SELECT * FROM shopping_items, we should see the following:

Item template rendering function

Adding checkboxes to the Shopping List page

Now let's create the HTML checkboxes for a user to be able to select a shopping item. We'll create the form to insert the data as follows:

//items.php 
 
<html> 
<body> 
 
<form action="post_profile.php" method="POST"> 
<table> 
  <input type="checkbox" value="<item_id>"> <td><item_image></td> 
  <td><item_name></td><td> 
 </table> 
</form> 
</body> 
</html> 

To do this, we'll need to modify our render_items method to add a checkbox:

public function render_items($itemsArray)  { 
 
foreach($itemsArray as $item) { 
  return '<tr> 
           <td><input type="checkbox" name="item[]" value="' . $item->id. '">' .  . '</td><td>' . $item->image .'</td> 
<td>'. $item->name . '</td> 
'<td>'.$item->price . '</td> 
'</tr>'; 
} 
} 

On the next page, when the user clicks on submit, we'll have to get all the IDs in an array.

Since we named our checkbox item[], we should be able to get the values via $_POST['item'] as an array. Basically, all the items that were checked will go into PHP's $_POST variable as an array, which will allow us to get all the values for saving our data into our database. Let's loop through the results' IDs and get the price for each in our database and save each item in an array called itemsArray, with the key as the name of the item and its price as the value of the item:

$db = new DB(); 
$itemsArray= []; //to contain our items - since PHP 5.4, an array can be defined with []; 
foreach($_POST['item'] as $itemId) { 
 
   $item = $db->read('shopping_items', 'id', $itemId); 
   //this produces the equivalent SQL code: SELECT * FROM shopping_items WHERE id = '$itemId'; 
   $itemsArray[$item->name] = $item-price;  
 
} 

We are going to first confirm with the user about the items that were purchased. We will just save the items and the total amount into a cookie for now. We will access the values of the cookie on our checkout page, which will accept the user's details and save them to our database on submission of the checkout page.

Tip

PHP session versus cookies: For data which is not very sensitive, such as the list of items a user has purchased, we can use cookies, which actually store the data (in plain text!) in the browser. If you are building this application and using it in production, it is recommended to use sessions. To learn more about sessions, go to http://php.net/manual/en/features.sessions.php .

Cookies in PHP

In PHP, to start a cookie, you just call the setcookie function. To save our items purchased into a cookie, we must serialize the array, the reason being, the cookies only store values as strings.

Here, we save the items into the cookie:

setcookie('purchased_items', serialize($itemsArray), time() + 900); 

The preceding cookie will store the items as an array in the purchased_items cookie. It will expire in 15 minutes (900 seconds). However, notice the call to the time() function, which returns the Unix timestamp of the current time. Cookies in PHP will expire when the time set in the last parameter has been reached.

Note

Debugging your cookie-based application is sometimes frustrating. Make sure that the timestamp generated by time() is really showing the current time.

For example, it could happen that you have recently reformatted your computer and for some reason was not able to set the time correctly. To test the time(), simply run a PHP script with the time() call and check http://www.unixtimestamp.com/ if they are almost the same.

Building the Checkout page

Finally, we'll create a form where the user can input their details after checking out.

We first need to build the database table for the customer. Let's call this table purchases. We'll need to store the customer's name, address, e-mail, credit card, items purchased, and the total. We should also store the time of the purchase transaction and use a unique primary key to index each row.

The following is our table's schema to be imported into our MySQL database:

CREATE TABLE purchases ( 
    id INT(11) NOT NULL AUTO_INCREMENT, 
    customer_name VARCHAR(255) NOT NULL, 
    address DECIMAL(6,2) NOT NULL, 
    email DECIMAL(6,2) NOT NULL, 
    credit_card VARCHAR(255) NOT NULL, 
    items TEXT NOT NULL, 
    total DECIMAL(6,2) NOT NULL, 
    created DATETIME NOT NULL, 
    PRIMARY KEY (id) 
); 

One way to import this is by creating a file purchases.sql, then logging in to your MySQL command-line tool.

Then, you can select the database you want to use with:

USE <databasename>

Finally, assuming you are on the same directory as purchases.sql, you can run:

SOURCE purchases.sql 

Let's finish off by creating a simple form with input fields for details such as the address, credit card, and name of the buyer:

<form action="save_checkout.php" method="post"> 
<table> 
  <tr> 
   <td>Name</td><td><input type="text" name="fullname"></td>  
  </tr>  
  
 <tr> 
<td>Address</td><td><input type="text" name="address"></td> 
</tr> 
<tr> 
<td>Email</td><td><input type="text" name="email"></td> 
</tr> 
 
<tr>  
  <td>Credit Card</td><td><input type="text" name="credit_card"></td> 
 </tr> 
<tr>  
  <td colspan="2"><input type="submit" name="submit" value="Purchase"></td> 
 </tr> 
 
</table> 
</form> 
 

Here is how it looks:

Building the Checkout page

Finally, we'll save everything into another table in our database by using our DB class as usual. To calculate the total amount, we will query the database for the prices and use the array_sum of PHP to get the total:

$db = new DB($server,$dbname,$name,$password); 
 
 
//let's get the other details of the customer 
$customer_name = $_POST['fullname']; 
$address = $_POST['address']; 
$email = $_POST['email']; 
$credit_card = $_POST['credit_card]; 
$time_now = date('Y-m-d H:i:s'); 
 
foreach($purchased_items as $item) { 
  $prices[] = $item->price; 
} 
 
 
//get total using array_sum 
$total = array_sum($prices); 
 
$db->insert('purchases', [ 
   'address' => $address, 
'email' => $email, 
'credit_card' => $credit_card, 
   'items' => //<all the items and prices>//, 
   'total' => $total, 
    'purchase_date' => $timenow 
  ]);  
?> 

To keep things simple, as you can see in the highlighted code, we need to collect all the items that were bought into one long string, for saving in our database. Here's how you can concatenate each item and their prices:

foreach($purchased_items as $item) { 
   $items_text .= $item->name ":" . $item->price .  "," 
} 

Then we can save this data into the variable $items_text. We will update the preceding highlighted code and change the text <all the items and prices> into it with  $items_text:

... 
  'items' => $items_text 
 ... 

The preceding foreach loop should be placed before the call to the $db->insert method in our code.

Thank you page

Finally, we've saved the data into our  purchased_items table. It's time to say thank you to our customer and send an e-mail. In our HTML code of thankyou.php, we will just write a thank you note and let the user know that an e-mail is on its way regarding their purchases.

Here's a screenshot:

Thank you page

We'll name the file thankyou.php, and its HTML code is pretty simple:

<!DOCTYPE html> 
<html> 
<head> 
   <!-- Latest compiled and minified CSS --> 
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> 
   <title>Thank you for shopping at example.info</title> 
</head> 
<body> 
 <div class="container"> 
        <div class="row"> 
            <div class="col-lg-12 text-center"> 
                <h1>Thank you for shopping at example.info</h1> 
                     <p>Yey! We're really happy for choosing us to shop online. We've sent you an email of your purchases. </p> 
                     <p>Let us know right away if you need anything</p> 
            </div> 
        </div> 
    </div> 
</body> 
</html> 

Sending an e-mail using PHP is done using the mail() function:

mail("<to address>", "Your purchase at example.com","Thank you for purchasing...", "From: <from address>"); 

The third parameter is the message of our e-mail. In the code, we still need to add the details of the purchase. We shall loop through the cookie we made earlier and the prices, then just output the total amount, and send the message:

$mail_message = 'Thank you for purchasing the following items'; 
$prices = []; 
$purchased_items = unserialize($_COOKIE['purchased_items']); 
foreach($purchased_items as $itemName => $itemPrice) { 
  $mail_message .=  $itemName . ": " .$itemPrice . "
 
"; 
  //since this is a plain text email, we will use 
 - which are escape strings for us to add a new line after each price. 
  $prices[] = $itemPrice; 
} 
 
$mail_message .= "The billing total of your purchases is " . array_sum($prices); 
 
mail($_POST['email'], "Thank you for shopping at example.info here is your bill", $mail_message, "From: [email protected]"); 

We can add the preceding bit of code at the very end of our thankyou.php file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72