Building a Webshop

In this tutorial, we are going to build a webshop, using PHP & MYSQL.

Things that will be in this webshop

  • Support for product categories
  • Support for product images
  • Support for customer registration
  • Support for invoice
  • Support for email



I will try my best, to keep this tutorial easy to understand.
There is a lot of work in creating a webshop, but it's something a lot of people are asking question about.

Part 1: Creating MYSQL tables

What are we going to need

  • A table for the products information
  • A table for the product categories
  • A table for the customers order
  • A table for the customers ordered products
  • A table for the customers information



Why do we need a table for the products and one for the categories ?

There are alot of reasons, but top two reasons would be

Speed, It's faster search on a number, then on text.
Edit , If you like to rename a group. Then you do it one place, and you don't need to rename all the products, because the group number will not change.

Products table

  CREATE TABLE products(
  `id` int NOT NULL AUTO_INCREMENT,
  `category_id` int NOT NULL,
  `name` varchar(200) NOT NULL,
  `description` text, 
  `price` DECIMAL(6,2) NOT NULL DEFAULT 0.00,
  `image` longblob,
   PRIMARY KEY (`id`),
   KEY (`category_id`)
  )

Categories table

  CREATE TABLE categories(
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
   PRIMARY KEY (`id`)
  )

Orders table

  CREATE TABLE orders(
  `id` int NOT NULL AUTO_INCREMENT,
  `customer_id` int NOT NULL,
  `created_date` timestamp NOT NULL,
   PRIMARY KEY (`id`),
   KEY(`customer_id`)
  )

Order products table

  CREATE TABLE order_products(
  `id` int NOT NULL AUTO_INCREMENT,
  `order_id` int NOT NULL,
  `product_id` int NOT NULL,
   PRIMARY KEY (`id`),
   KEY(`product_id`)
  )

Customers table

  CREATE TABLE customers(
  `id` int NOT NULL AUTO_INCREMENT,
  `firstname` varchar(200) NOT NULL,
  `lastname` varchar(200) NOT NULL,
  `adresse` varchar(200) NOT NULL,
  `city` varchar(200) NOT NULL,
  `zip` varchar(10) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
   PRIMARY KEY (`id`),
   KEY (`email`)
  )

Part 2: Creating PHP Classes

We are going to create a set of classes.

What are we going to need

  • A config file with information about the database, image size of the products and etc..
  • A class for talking to the database
  • A class for handling the customers basket
  • A class for handling the categories
  • A class for handling the products
  • A class for handling the orders
  • A class for handling the emails
  • A class for handling the customers
  • A class for handling the invoice

Config file

filename: webshop_conf.php

 <?php
 
     /* MYSQL Configuration */
 
      $mysql_server    = "server.name.com";
      $mysql_database  = "webshop_database";
      $mysql_username  = "john.doe";
      $mysql_password  = "secretpassword";
 
 
     /* Upload Image Configuration */
 
      // Image scale in pixel 
      $image_height    = 125;
      $image_width     = 125;
 
     /* Webshop Configuration */
 
     $webshop_email    = "webshop@john.doe.com"; 
 
     /* Display of currency */
 
     // US currency
     $webshop_currency = "US Dollars";
     $webshop_currency_prefix = "$";
 
     // Danish currency
     // $webshop_currency = ",- kr";
     // $webshop_currency_prefix = "";
 
     /* WAT (TAX) defined in % */
     $webshop_wat     = "25";
 
 
 ?>

Database class

filename: database.php

 <?php
class Database{
  var $server;
  var $username;
  var $password;
  var $database;
  var $error;
  var $lastid;
  var $effectedrows;
  var $errorNo;
  var $debug = false;
 
  function connect(){
      @mysql_connect($this->server,$this->username,$this->password);
      @mysql_select_db($this->database);
 
      // In case of error
      $this->errorNo = mysql_errno();
      $this->error=mysql_error();
  }
 
  function disconnect(){
      @mysql_close();
  }
 
  function execute($sql) {
      // Get resultset
      $result = mysql_query($sql);
 
      // In case of a insert then get last inserted ID
      $this->lastid=mysql_insert_id();
 
      // in case of update/delete or select get affected rows
      $this->effectedrows=mysql_affected_rows();
 
      // In case of error
      $this->errorNo=mysql_errno();
      $this->error=mysql_error();
 
      // in Case of debug!
      if ($this->debug){
         print 'Called with SQL <br /><pre>' . $sql . '</pre><br />';
      }
      return $result;
 }
}
 ?>

Basket class

filename: basket.php

 <?php
 
   //Make sure session is activated
   @session_start();
 
   class Basket {
     var $basket;
     var $database;
 
     function Basket(){
       //When basket is created, then load basket from session
       $this->basket = $_SESSION['webshop_basket'];
       $this->init();
     }
 
     function init(){
       // include webshop confication
       include("webshop_conf.php");  
 
       $this->database = new Database(); 
 
       // setup database class
       $this->database->server=$mysql_server;
       $this->database->database=$mysql_database;
       $this->database->username=$mysql_username;
       $this->database->password=$mysql_password;
     }
 
     function add($product_id){
       // add product_id to basket array
       $this->basket[] = $product_id;
       $this->save();
     }
 
     function remove($index){
       //remove a single element from basket array
       for ($i=0;$i<count($this->basket);$i++) 
           if ($i != $index) $tmp[] = $this->basket[$i];
       $this->basket = $tmp;
       $this->save();
     }
 
     function save(){
       //store basket in session
       $_SESSION['webshop_basket'] = $this->basket;
     }
 
     function clear(){
       //clear basket
       unset($_SESSION['webshop_basket']);
       unset($this->basket);
       $this->basket = $_SESSION['webshop_basket'];
     }
 
     function totalPrice(){
      //make sure there are products in the basket
       if (count($this->basket) < 1) return 0;
      // connect to database
       $this->database->connect();
 
       //get product id's
       $products = join(',',$this->basket);
       // load a single product
       $result = $this->database->execute("select sum(price) as total from products where id in (" . $products . ")"); // ordered by name       
 
       //read total
       if ($row=mysql_fetch_assoc($result)){
           $total = $row['total'];
       }
       // disconnect from database
       $this->database->disconnect();
 
       //return total  
       return $total;  
 
    }
 
   } 
?>

Categories class

filename: categories.php

<?php
 
   //include the product class
   include("product.php");
 
   class Categories {
     var $categories;
     var $products;
     var $database;
 
     function Categories($category_id=null){
       $this->init();
       $this->load();
       if ($category_id != null)
         $this->loadproducts($category_id);
     }
 
 
     function load(){
       // connect to database
       $this->database->connect();
 
       // load categories
       $result = $this->database->execute("select * from categories order by 2"); // ordered by name
 
       while ($row=mysql_fetch_assoc($result)){
          $this->categories[] = array('id'=>$row['id']  ,'name'=>$row['name']);
       }
 
       // disconnect from database
       $this->database->disconnect();
     }
 
     function loadproducts($category_id){
        $product  = new Product();
        $this->products = $product->loadproducts($category_id);
     }
 
     function init(){
       // include webshop confication
       include("webshop_conf.php"); 
       $this->database = new Database(); 
 
       // setup database class
       $this->database->server=$mysql_server;
       $this->database->database=$mysql_database;
       $this->database->username=$mysql_username;
       $this->database->password=$mysql_password;
     }
  } 
 ?>

Product class

filename: Product.php

<?php
 
   class Product {
    var $id;
    var $category_id;
    var $name;
    var $description;
    var $price;
    var $image;
    var $database;
 
     function Product($id=null){
       $this->init();
       if ($id!=null)  
       $this->load($id);
     }
 
 
     function load($id){
       // connect to database
       $this->database->connect();
 
       // load a single product
       $result = $this->database->execute("select * from products where id='" . $id . "'"); // ordered by name
 
       while ($row=mysql_fetch_assoc($result)){
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$this->$key = $value;
          }
       }
 
       // disconnect from database
       $this->database->disconnect();
     }
 
     // load all products from a category
     function loadproducts($category_id){
       // connect to database
       $this->database->connect();
 
       // load a single product
       $result = $this->database->execute("select * from products where category_id='" . $category_id . "'"); // ordered by name       
 
       while ($row=mysql_fetch_assoc($result)){
          //Create a new products
          $product = new Product();  
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$product->$key = $value;
          }
          //store product in array
          $products[] = $product; 
       }
 
       // disconnect from database
       $this->database->disconnect();
 
       //return array of products  
       return $products;  
     } 
 
     function init(){
       // include webshop confication
       include("webshop_conf.php");  
       $this->database = new Database(); 
 
       // setup database class
       $this->database->server=$mysql_server;
       $this->database->database=$mysql_database;
       $this->database->username=$mysql_username;
       $this->database->password=$mysql_password;
     }
  } 
 ?>

Customer class

filename: customer.php

<?php 
   class Customer {
    var $id;     
    var $firstname;  
    var $lastname;  
    var $adresse;    
    var $city;     
    var $zip;     
    var $phone; 
    var $email;   
    var $password; 
    var $database;
 
     function Customer($id=null){
       $this->init();
       if ($_SESSION['webshop_customer'] != "") $this->load($_SESSION['webshop_customer']);
       if ($id!=null) $this->load($id);
     }
 
     function load($id){
       // connect to database
       $this->database->connect();
 
       // load a single customer
       $result = $this->database->execute("select * from customers where id='" . $id . "'"); // ordered by name
 
       while ($row=mysql_fetch_assoc($result)){
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$this->$key = $value;
          }
       }
 
       // disconnect from database
       $this->database->disconnect();
     }
 
     function login($email,$password){
       // connect to database
       $this->database->connect();
 
       // load a single customer
       $result = $this->database->execute("select * from customers where email='$email' and password=PASSWORD('$password')"); 
 
       if ($row=mysql_fetch_assoc($result)){
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$this->$key = $value;
          }
       }
 
       // disconnect from database
       $this->database->disconnect();
 
       //set customer in the session
       if ($this->firstname != "")  @$_SESSION['webshop_customer'] = $this->id;  
 
       //return if the customer was found! 
       if ($this->firstname != "") return true;
       else return false;
 
 
     }
 
     function create(){
       // connect to database
       $this->database->connect();
 
       // create a single customer
       $result = $this->database->execute("insert into customers values('','" . $this->firstname 
                                                                      . "','" . $this->lastname 
                                                                      . "','" . $this->adresse 
                                                                      . "','" . $this->city 
                                                                      . "','" . $this->zip 
                                                                      . "','" . $this->phone 
                                                                      . "','" . $this->email 
                                                                      . "',PASSWORD('" . $this->password . "'))");
       //Load newly create customer 
        $this->load(mysql_insert_id());  
 
       // disconnect from database
       $this->database->disconnect();
       return $this->login($this->email,$this->password);
     }
 
 
     function init(){
       // include webshop confication
       include("webshop_conf.php");  
 
       $this->database = new Database(); 
 
       // setup database class
       $this->database->server=$mysql_server;
       $this->database->database=$mysql_database;
       $this->database->username=$mysql_username;
       $this->database->password=$mysql_password;
     }
  } 
 ?>

Orders class

filename: orders.php

<?php
 
   class Orders {
    var $id;     
    var $customer_id;     
    var $customer;     
    var $created_date;
    var $products;
    var $database;
 
     function Orders($id){
       $this->init();
       if($id!=null)
        $this->load($id)
     }
 
     function load($id){
       // connect to database
       $this->database->connect();
 
       // load a single product
       $result = $this->database->execute("select * from orders where id='" . $id . "'"); // ordered by name
 
       while ($row=mysql_fetch_assoc($result)){
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$this->$key = $value;
          }
       }
 
       //load customer data
       $this->customer = new Customer($this->customer_id);
 
 
       // load a single product
       $result = $this->database->execute("select * from order_products where order_id='" . $id . "'"); // ordered by name       
 
       while ($row=mysql_fetch_assoc($result)){
          //Create a new products
          $product = new Product();  
          // dynamic fill out all fields from row 
          foreach($row as $key => $value){
             @$product->$key = $value;
          }
          //store product in array
          $this->products[] = $product; 
       }
 
 
       // disconnect from database
       $this->database->disconnect();
     }
 
     function init(){
       // include webshop confication
       include("webshop_conf.php");  
 
       $this->database = new Database(); 
 
       // setup database class
       $this->database->server=$mysql_server;
       $this->database->database=$mysql_database;
       $this->database->username=$mysql_username;
       $this->database->password=$mysql_password;
     }
  } 
 ?>

Email class

filename: email.php

<?php 
 
class Email {
    var $to,$from,$subject,$text,$files="";
 
    //Send email
    function send(){
 
     $filetype             = "application/octet-stream"; 
     $options              = "From: " . $this->from;
 
     $semi_rand = md5(time()); 
     $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
     //Write the mime message
     $options            .= "\nMIME-Version: 1.0";
     $options            .= "\nContent-Type: multipart/mixed;\n boundary=\"". $mime_boundary ."\"\n\n";
 
     $content            .= "This is a multi-part message in MIME format.\n\n";
     $content            .= "--$mime_boundary\n";
 
 
     // Adding the text
     $content          .= "Content-Type: text/html; charset=iso-8859-1\n";
     $content          .= "Content-Transfer-Encoding: 8bit\n\n";
     $content          .= $this->text . "\n\n";
 
     // check if $files is empty
     if ($this->files != "") { 
        // Se if $files is a array of files
        if (is_array($this->files)){      
          for($i=0;$i<count($this->files);$i++){
            //Read the file
            $handle         = fopen($this->files[$i], 'rb');
            $filecontents   = fread($handle, filesize($this->files[$i]));
            fclose($handle);
 
            //base64 encode the file
            $filecontents   = @base64_encode($filecontents);        
 
            // Adding the file
            $content          .= "--". $mime_boundary . "\n";
            $content          .= "Content-Type: application/octet-stream; name=\"" . basename($this->files[$i]) . "\"\n";
            $content          .= "Content-Transfer-Encoding: base64\n\n";
            $content          .= chunk_split($filecontents) . "\n\n";
          }
        } else {
          // $files is just a single file
          //Read the file
          $handle         = fopen($this->files, 'rb');
          $filecontents   = fread($handle, filesize($this->files));
          fclose($handle);
 
          //base64 encode the file
          $filecontents   = @base64_encode($filecontents);        
 
          // Adding the file
          $content          .= "--". $mime_boundary . "\n";
          $content          .= "Content-Type: application/octet-stream; name=\"" . basename($this->files) . "\"\n";
          $content          .= "Content-Transfer-Encoding: base64\n\n";
          $content          .= chunk_split($filecontents) . "\n\n";
        }
          // Add last mime_boundary
          $content          .= "--". $mime_boundary . "\n";
     }
 
     //Send the mail
     mail($this->to,$this->subject,$content,$options);
  }
 
 }
 
?>

Part 3: Creating HTML pages

Part 4: Creating a Admin page

 
building_a_webshop.txt · Last modified: 2007/10/16 04:46 by gq
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki