A Shopping Cart using PHP Sessions

This posts illustrates a relatively simple shopping cart in PHP using sessions to store cart details, quantities and total cart amount.  The cart has an add to cart button , remove from cart button and displays the total value of the cart.

This post is taken from part of the book PHP Tutorials: Programming with PHP and MySQL which is available as a paper back printed version or as a downloadable Kindle version. Click here for paper back version.

The following listing is the complete shopping cart in PHP:

<?php session_start();
#cart.php - A simple shopping cart with add to cart, and remove links
 //---------------------------
 //initialize sessions

//Define the products and cost
$products = array("product A", "product B", "product C");
$amounts = array("19.99", "10.99", "2.99");

//Load up session
 if ( !isset($_SESSION["total"]) ) {
   $_SESSION["total"] = 0;
   for ($i=0; $i< count($products); $i++) {
    $_SESSION["qty"][$i] = 0;
   $_SESSION["amounts"][$i] = 0;
  }
 }

 //---------------------------
 //Reset
 if ( isset($_GET['reset']) )
 {
 if ($_GET["reset"] == 'true')
   {
   unset($_SESSION["qty"]); //The quantity for each product
   unset($_SESSION["amounts"]); //The amount from each product
   unset($_SESSION["total"]); //The total cost
   unset($_SESSION["cart"]); //Which item has been chosen
   }
 }

 //---------------------------
 //Add
 if ( isset($_GET["add"]) )
   {
   $i = $_GET["add"];
   $qty = $_SESSION["qty"][$i] + 1;
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
   $_SESSION["cart"][$i] = $i;
   $_SESSION["qty"][$i] = $qty;
 }

  //---------------------------
  //Delete
  if ( isset($_GET["delete"]) )
   {
   $i = $_GET["delete"];
   $qty = $_SESSION["qty"][$i];
   $qty--;
   $_SESSION["qty"][$i] = $qty;
   //remove item if quantity is zero
   if ($qty == 0) {
    $_SESSION["amounts"][$i] = 0;
    unset($_SESSION["cart"][$i]);
  }
 else
  {
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
  }
 }
 ?>
 <h2>List of All Products</h2>
 <table>
   <tr>
   <th>Product</th>
   <th width="10px">&nbsp;</th>
   <th>Amount</th>
   <th width="10px">&nbsp;</th>
   <th>Action</th>
   </tr>
 <?php
 for ($i=0; $i< count($products); $i++) {
   ?>
   <tr>
   <td><?php echo($products[$i]); ?></td>
   <td width="10px">&nbsp;</td>
   <td><?php echo($amounts[$i]); ?></td>
   <td width="10px">&nbsp;</td>
   <td><a href="?add=<?php echo($i); ?>">Add to cart</a></td>
   </tr>
   <?php
 }
 ?>
 <tr>
 <td colspan="5"></td>
 </tr>
 <tr>
 <td colspan="5"><a href="?reset=true">Reset Cart</a></td>
 </tr>
 </table>
 <?php
 if ( isset($_SESSION["cart"]) ) {
 ?>
 <br/><br/><br/>
 <h2>Cart</h2>
 <table>
 <tr>
 <th>Product</th>
 <th width="10px">&nbsp;</th>
 <th>Qty</th>
 <th width="10px">&nbsp;</th>
 <th>Amount</th>
 <th width="10px">&nbsp;</th>
 <th>Action</th>
 </tr>
 <?php
 $total = 0;
 foreach ( $_SESSION["cart"] as $i ) {
 ?>
 <tr>
 <td><?php echo( $products[$_SESSION["cart"][$i]] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><?php echo( $_SESSION["qty"][$i] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><?php echo( $_SESSION["amounts"][$i] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><a href="?delete=<?php echo($i); ?>">Delete from cart</a></td>
 </tr>
 <?php
 $total = $total + $_SESSION["amounts"][$i];
 }
 $_SESSION["total"] = $total;
 ?>
 <tr>
 <td colspan="7">Total : <?php echo($total); ?></td>
 </tr>
 </table>
 <?php
 }
 ?>

The cart example uses the following sessions to maintain the state of the cart:

$_SESSION[“qty”][i] Stores the quantity for each product
$_SESSION[“amounts”][i] Stores the price from each product
$_SESSION[“cart”][i] Identifies which items have been added to the cart
$_SESSION[“total”] Stores the total cost

The sessions are actually arrays so in the case of:

$_SESSION[“qty”][i]

is the quantity for the element with number i.

Description of the PHP shopping cart code

We start by defining PHP to use sessions by:

session_start();

This has to be at the very top of the PHP page.

Next we set up our products and populate our sessions. In this example we are using a fixed array of product descriptions and amounts. You may want to do this in your application or you could read in the data into the $product and $amounts array from a database.

//---------------------------
 //initialise sessions

 //Define the products and cost
 $products = array("product A", "product B", "product C");
 $amounts = array("19.99", "10.99", "2.99");

 if ( !isset($_SESSION["total"]) ) {

  $_SESSION["total"] = 0;

  for ($i=0; $i< count($products); $i++) {
   $_SESSION["qty"][$i] = 0;
   $_SESSION["amounts"][$i] = 0;
 }
}

The following code will reset and clear the sessions when the Reset Cart link is selected.

//---------------------------
  //Reset
  if ( isset($_GET['reset']) )
   {
    if ($_GET["reset"] == 'true')
    {
     unset($_SESSION["qty"]); //The quantity for each product
     unset($_SESSION["amounts"]); //The amount from each product
     unset($_SESSION["total"]); //The total cost
     unset($_SESSION["cart"]); //Which item has been chosen
   }
}

The following code adds an item to the sessions when the ‘Add to Cart’ link is clicked:

//---------------------------
//Add
if ( isset($_GET["add"]) )
{
$i = $_GET["add"];

$qty = $_SESSION["qty"][$i] + 1;

$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
$_SESSION["cart"][$i] = $i;
$_SESSION["qty"][$i] = $qty;
}

and the following deletes an item from the cart when the ‘Delete from Cart’ link is clicked:

 //---------------------------
 //Delete
 if ( isset($_GET["delete"]) )
 {
   $i = $_GET["delete"];
   $qty = $_SESSION["qty"][$i];
   $qty--;
   $_SESSION["qty"][$i] = $qty;

 //remove item if quantity is zero
 if ($qty == 0) {
   $_SESSION["amounts"][$i] = 0;
   unset($_SESSION["cart"][$i]);
 }
 else
 {
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
 }
 }

The rest of the code is the visual display using a table and various loops to show the product lists and the cart details together with the links.

This post is taken from part of the book PHP Tutorials: Programming with PHP and MySQL which is available as a paper back printed version or as a downloadable Kindle version. Click here for paper back version.

PHP-eSeller is a complete application that utilizes a shopping cart using PHP Sessions and is available from here:

Click here to go to PHP-eSeller web page

PHP-KeyCodes now has free button facility

PHP-KeyCodes is used to sell software license key codes or pin numbers after payment from PayPal. It is a PHP script which you can purchase from the withinweb.com web site. PayPal buttons are generated by the PHP script which can be added on to your website on any page allowing you to integrate the buttons into existing web pages.

PHP=KeyCodes now has a feature that allows you to send a code to a customer without them making a payment.

The customer enters their email address and the next key code is sent.

You then have a list of customers in your database which you can extract and use for marketing purposes.

For a full description of PHP-KeyCodes refer to:

http://www.withinweb.com/phpkeycodes

Sell key codes from your web site

The advantage with PHP-KeyCodes is that you do not have to use third party companies to manage you sells.  You can purchase this PHP script and install it on your own web site so that all your key codes and license codes are always under your control.  The PHP script uses PayPal IPN to make sure that the customer does not get hold of a license code unless they have made a valid and complete purchase.

The PHP script is able to manage all situations that can occur with PayPal purchases, such as buying with an e-check.

Word Large Documents with different header / footer

It is not immediately obvious how to do different header / footer for different Chapters in a long document.

The main control of this is by section breaks.  For each section that requires a different header / footer you use a new section break.

In word 2013, go to “PAGE LAYOUT” and select “Breaks”.  In the drop down list select Section Breaks -> Next Page
This inserts a section break and starts a new section on the next page.  Other versions of word will be similar.

Create your header in the normal way by double clicking on the head of the Word document.

Once you have your section breaks set up, the next important step is to control the linking between headers in different sections.  To do this you go into editing of the header by double clicking on it.  In the menu bar you should see “Link to Previous”.  If you are in the second section of a document, you click on this to unlink the header of the second section.  You can then edit the header in the second section and that will allow you to have a different header in that second section.

You can now do other clever things such as different header / footer for odd / even pages and that is controlled from the header menu bar by ticking the appropriate tick boxes.

Formatting for Kindle eBooks – Hints, Tips and Tricks

There are a number of articles on formatting an e-book for Kindle so I thought I would contribute my thoughts and ideas so far.

The most common way to create a Kindle e-book is to use Microsoft Word because it includes easy editing features, table of content generation, spell checker, control of style sheets and so on.

You then do a “save as” to HTML from Word to create an HTML document and then apply any adjustments in the HTML code itself. You can create a book from HTML but it would require much more editing. Amazon then takes the HTML document, and converts it to the required format for Kindle devices.

So the principles are:

  • Create a separate Word file for each chapter of your book.
  • Format your document using styles.
  • Create a combined master Word file of all your chapters.
  • Expand the master file into one Word document.
  • Do a Ctrl-A to select all the text and then copy all the text into a new blank Word document.
  • Do a Save As to Filtered HTML so that you end up with one large HTML file with the images in a separate folder.
  • Do some final adjustments and tweaks to the HTML by hand.
  • Preview your HTML in an Amazon previewer application.
  • Zip up the HTML plus the images and then upload to Amazon.
  • Create a cover image and submit it to Amazon.

Word Template
I have included my template for Word which has been quite successful so far. However, I still find I have to do some changes to the HTML by hand.

Click here to download my zip file which includes a Microsoft Word template system.

Word format for Kindle

Font Face
Font face can be whatever you want as Kindle will uses its own default font and the user can define their own font face.

However, you usually select Caliba 11pt

Tabs
Tabs don’t transpose all that well into HTML so it is best to remove any tabs in the Word text. This can be done by searching for ^t

Bullets
Word formatted bullets do not work correctly because they use tabs and have images which don’t seem to convert correctly into HTML I would suggest to use normal unformatted paragraphs but with the * character to represent the bullet.

Tables
Y
ou can use tables in latest Amazon Kindles and you can colour the rows. You have to be careful if the text does not wrap in which case you have to force a line to wrap.

Pictures
Images should be inserted in JPEG (or .jpeg) format with centre alignment (don’t copy and paste from another source).

Select “Insert” > “Picture” >

It is recommended that images are saved at 300 dpi at about 640 pixels wide. The image should not be greater than 127kbyte (63kbyte on older Kindles) so use 300 dpi unless the image file size is too big.

Expanding the sub documents
When you expand the Word documents into one single Word document, do a “copy all” and paste into a new word document to copy the text over. I have found this to be the best method as it removes any dependencies to other sub document files that you may have.

Save as HTML
Once you have completed the formatting in Word and have one combined word document with index pages, preface and so on, you save it as “HTML Word Filtered” and then you should test it in a Kindle viewer and with a web browser.

File -> Save as…

select the location where you want to save the file, and in the “Save as type” drop down list, select

“Web Page, Filtered (*.htm, *.html)”

This will create the HTML page and a folder with all the required images. You should then go through the HTML code and make changes manually.

Editing the HTML
I have found issues with images which I can only seem to fix manually in the HTML code by changing the images to

width=”100%”

and

align=”center”

so that the image scales to fit the width of the page. Note the align=”center” which forces the text to go to the bottom of the image instead of wrapping around it.

When you upload the document to Amazon it converts it so that every first line of each paragraph has an automatic indent.

This seems to be because an assumption by Amazon that all first lines should have an indent and all paragraphs should be justified. For some books this is fine, but personally I don’t like first line indents or justified text.

To overcome this, edit the styles for various p tags with the addition of

text-indent: 0px;

to stop tab indexing.

I have now modified all my Word styles with a first line indent of 0.01.  This is for the normal style.  This has the effect of overriding the Amazon indent style so you dont have to do anything about this.

If you want to set this up yourself, go to the “normal” style, right click on it and and select Modify. Then select Format.. button and then Paragraph… Then in the Special drop down list select First Line and in the amount, enter 0.01cm.

You may want to go into the HTML and search for justify in the HTML code and remove those entries.

Also Amazon displays text as justified so I then edit the HTML styles by hand to add in

text-align:left;

on all paragraph tags. This will cause the text not to be left formatted without justification.

Uploading to Amazon
Once you have your complete HTML document with any images, you should then upload it to Amazon. When you converted to from Word to HTML it would have created a folder of images as well as the HTML file itself. Zip all the files up including the image folder and upload the single zip file. Amazon will unzip and convert and publish the HTML document.

The book Cover image

Kindle has an article on creating a book cover image at:

https://kdp.amazon.com/self-publishing/help?topicId=A2J0TRG6OPX0VM

Essentially this says that there are two types of files for cover images:

JPEG, or .jpeg
TIFF, or .tif(f)

Do not optimise the images as the Amazon process applies its own compression to images when displaying them on its website.
Dimensions
The dimensions of the image should have an ideal height/width ratio of 1.6 so this means:

• A minimum of 625 pixels on the shortest side and 1000 pixels on the longest side
• For best quality, your image would be 1563 pixels on the shortest side and 2500 pixels on the longest side

Colour
Colour images use the standard web RGB (red, green, blue) system which is native to the web and screen displays.
You should use colour images whenever possible and relevant. The Kindle reading device has a black and white display other devices such as the PC and iPhone use colour fonts and images.

Borders for White Cover Art
Cover art with white or very light backgrounds can seem to disappear against the white background.
Adding a very narrow (3-4 pixel) border in medium gray will define the boundaries of the cover.
Some tips for marketing ebooks

The important aspect of a book is the quality. The better the quality the more it will sell. Quality can be many things such as consistency of writing style, formatting of tables, good quality images and so on.
Here are a few tips that may help to market your eBooks:
1 Design a cover that jumps out at you from the amazon store displays. It should look good at full size and as a thumbnail. Make sure that the thumbnail image is readable and recognisable. If you cannot create a good quality cover, then employ a design service to do it for you.
2. Carefully edit and proofread for spelling, grammar and style.
3. Amazon requires a description of the book so make sure that this is interesting and informative.
4. Fill in your author profile at Amazon Author Profile to give information about yourself to your potential readers. Combine this with a blog to keep readers informed about changes to your book.
5. Promote your book online using the standard social networks such as Facebook and Twitter. You can also create a web site for you book providing information and links, promote your book on other sites, message boards and other communities.
6. Create a promotional video and book trailer and upload it to your web site, blog or to your Amazon Author Profile page.
7. Create a physical version of your book using CreateSpace which is a print on demand system.
8. Join the Amazon Associates program to earn an additional 4% on each sale. You can add links to your web pages and gain an additional 4% on each sale when a customer clicks through.

Amazon Reviews for your Books

The Amazon reviews can have a huge effect on your book sales.  You need to be popular to become popular which can be tricky when you first make a book available.

You need to drive as many reviews to your book as possible so try to get your friends and family to do a review each.  A minimum of 4 or 5 is really good but up to 10 is what you need.

The number of reviews a book has is a good indicator to a possible purchaser as to how serious they should consider it.

As a self publisher you have to take responsibility to make sure this section is populated which means promoting it in wherever you can.  Unfortunately, a genuine review is usually only made when the customer either really loves it or really hates it.

Once you have got going with reviews you should be able to rely on your normal sales to get further reviews.

Book Front Cover Layout and Design

Creating a stand out front cover is a must to get your book noticed on web sites and in book shop shelves – if you are lucky to get your book that far.

The front cover needs to be smart, professional and not too complicated. Your potential purchaser will see it as an indication of the quality of what is inside if the outside looks good.

As you will probably be selling an eBook version, you need to have a thumbnail image which can be placed on web sites and will be used as the image on sites like Amazon. This has particular display issues as you must use fonts, images and graphics that are clear to read even when the cover is reduced to a thumbnail. Make sure that there is sufficient contrast between the background colours and the text. Don’t forget the back cover where you can add some text to advertise your book.

Web links:

An article from the Book Designer:
http://www.thebookdesigner.com/2012/01/book-cover-design-and-the-problem-of-symbolism/

a simple On line cover designer:
https://www.createspace.com/Tools/CoverCreator.jsp

A free free on line graphics program which has many of the functionality of PhotoShop:
http://pixlr.com/

How to remove unwanted styles from Microsoft Word

I use Word to write and format my eBook and printed version of the book because it is easy to use and is a common platform with plenty of online help.  However, it has take me a very long time to become comfortable with styles.

The main issue I have had is how to removed unwanted styles.  I found that my styles list was made up of styles with similar names.  So I had one style called CODEBLOCK and others called CODEBLOCK1 , CODEBLOCK2, CODEBLOCK3 and so on.  In some documents this amounted to thousands of unwanted duplicate styles which slowed down loading the file.

I don’t know how these were created, it may have been something to do with Master Pages or possible to do with copying text from one document to another.  It made the document larger than necessary and when I did saved the file as HTML I ended up with a massive list of css styles in the HTML document.

I tried a number of methods, one of which was to run a Word make to delete unused styles.  This particular macro seemed to work on small documents, but caused Word to hang up when I tried it on large documents.

Eventually I found a way of getting rid of them but event this method can take a a few minutes per file.

First you need to show the styles window which will look something like:

styles

Click on Manage Styles icon at bottom of display.
Click on Import/Export…

This display allows you to select multiple styles in the left hand column and then delete the multiple styles.

Use the mouse button with the Ctrl key to select the multiple styles and then delete them.  Note that you cannot delete built in styles and also this displays allows you to move styles from one document to another.

Next step for PHP Tutorials eBook

The eBooks is on sale on the Amazon web site and hence is available for Kindle devices.  It is also available as a PDF download which may be purchased from my web site http://www.paulvgibbs.com.

The next step is to make the eBook more widely available through other stores and other formats and to create a forum where purchasers of the book can more easily ask questions and discuss PHP coding issues.

In the mean time you are quite welcome to ask questions via my email.