Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

5 Steps Simple PHP Referral System

INTRODUCTION
THE SALES BOOSTER

Welcome to a tutorial and example on how to create a simple PHP Referral system. So you have a website that already sells some products, and looking to boost the sales a little bit more. A referral system may be able to help with that, but it does require some technical skill to put one in place. Just how do we do it? This guide will walk you through the steps – Read on to find out!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
Overview & Assumptions

Section B
The Database

Section C
Core Libraries

Section D
The Process Steps

Extra
Download & More

Closing
What’s Next?

SECTION A
OVERVIEW & ASSUMPTIONS

Before we dive into the code, let us get started with an overview of how the system works first. Also, here are some of my assumptions – So that you know what to expect from this guide.

ASSUMPTIONS & NOTES

Most of you guys here should already have an existing website that is selling some stuff, and just want a referral system “extension”. With that, we shall not reinvent the wheel and create yet another shopping cart nor users system nor login system.

Also, this guide will only touch on the board mechanics. We shall not go into the details for “how to implement for Shopify, Magento, Drupal, WordPress, whatever else is out there” – Or this guide will never end… More importantly, no free lunch will be given to those who are working on paid projects. You have to earn your own pay cheque.

SYSTEM OVERVIEW

This will be the process flow of the entire system in general.

  • Referrals will sign up for your program.
  • The system will generate unique referral links, and your referrals will proceed to promote using these links.
  • Customers will make purchases using those links.
  • We credit the sales to the respective referrals.
  • Finally, we can generate sales reports and pay the commissions accordingly.

But as with the notes above, everyone will have a different system and a different approval process. We will not go deep into referral signup nor recreate an entire shopping cart.

SECTION B
THE DATABASE

Now that we are done with the system overview, let us start with an introduction to the very foundation of the system – The database tables.

REFERRALS TABLE

First, we need to have a table to hold all the information of your referrals.

sql/referral.sql
CREATE TABLE `referral` (
  `referral_id` int(11) NOT NULL,
  `referral_name` varchar(255) NOT NULL,
  `referral_email` varchar(255) NOT NULL,
  `referral_password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `referral`
  ADD PRIMARY KEY (`referral_id`),
  ADD UNIQUE KEY `referral_name` (`referral_name`),
  ADD UNIQUE KEY `referral_email` (`referral_email`);

ALTER TABLE `referral`
  MODIFY `referral_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
FieldDescription
referral_idThe primary key, auto-increment.
referral_nameUnique user name, used for the referral link.
referral_emailThe referral’s email, unique to prevent multiple registrations.
referral_passwordThe password.

Is this not a user table? Yes, sort of. You can actually modify your existing user table if you want, and just add another “user role” column to distinguish between the administrators, customers, and referrals. But for the sake of a “non-destructive” example, we will be using this table instead.

REFERRAL SALES TABLE

Next, we will need a table to hold all the referral sales.

sql/referral-sales.sql
CREATE TABLE `referral_sales` (
  `referral_id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `order_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `order_amount` decimal(10,2) NOT NULL,
  `order_commission` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `referral_sales`
  ADD PRIMARY KEY (`referral_id`,`order_id`),
  ADD KEY `order_date` (`order_date`);
COMMIT;
FieldDescription
referral_idPartial primary key and foreign key.
order_idPartial primary key and foreign key.
order_dateDate of sale.
order_amountTotal order amount.
order_commissionCommission amount given to the referral.

Again, we could have just added a referral ID to your existing orders table. But to avoid messing with your existing project, we shall work on this separate sales table.

SECTION C
CORE LIBRARIES

Now that we have established the database tables, let us move on with the scripts. In this section, we will be introducing the server side library files that will do all the processing work. You may already have chosen a framework for your own project, and that is all fine – Just treat this as an example, and switch to use your own framework in your own project. 

CONFIG FILE

lib/config.php

The first script that we have is a config file, just a place to store all the settings and stuff. Please remember to change the database settings to your own.

DATABASE LIBRARY

lib/lib-db.php
pdo = new PDO(
        $str, DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES => false
        ]
      );
    }

    // ERROR - CRITICAL STOP - THROW ERROR MESSAGE
    catch (Exception $ex) {
      print_r($ex);
      die();
    }
  }

  function __destruct () {
  // __destruct() : close connection when done

    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  function exec ($sql, $data=null) {
  // exec() : run insert, replace, update, delete query
  // PARAM $sql : SQL query
  //       $data : array of data

    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      $this->lastID = $this->pdo->lastInsertId();
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return true;
  }

  function start () {
  // start() : auto-commit off

    $this->pdo->beginTransaction();
  }

  function end ($commit=1) {
  // end() : commit or roll back?

    if ($commit) { $this->pdo->commit(); }
    else { $this->pdo->rollBack(); }
  }

  function fetchAll ($sql, $cond=null, $key=null, $value=null) {
  // fetchAll() : perform select query (multiple rows expected)
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $key : sort in this $key=>data order, optional
  //       $value : $key must be provided. If string provided, sort in $key=>$value order. If function provided, will be a custom sort.

    $result = [];
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      // Sort in given order
      if (isset($key)) {
        if (isset($value)) {
          if (is_callable($value)) {
            while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
              $result[$row[$key]] = $value($row);
            }
          } else {
            while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
              $result[$row[$key]] = $row[$value];
            }
          }
        } else {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row;
          }
        }
      }
      // No key-value sort order
      else {
        $result = $this->stmt->fetchAll();
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    // Return result
    $this->stmt = null;
    return count($result)==0 ? false : $result ;
  }

  function fetch ($sql, $cond=null, $sort=null) {
  // fetch() : perform select query (single row expected)
  //           returns an array of column => value
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $sort : custom sort function

    $result = [];
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      if (is_callable($sort)) {
        while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
          $result = $sort($row);
        }
      } else {
        while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
          $result = $row;
        }
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    // Return result
    $this->stmt = null;
    return count($result)==0 ? false : $result ;
  }

  function fetchCol ($sql, $cond=null) {
  // fetchCol() : yet another version of fetch that returns a flat array
  // I.E. Good for one column SELECT `col` FROM `table`

    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute($cond);
    $result = $this->stmt->fetchAll(PDO::FETCH_COLUMN, 0);
    return count($result)==0 ? false : $result;
  }
}

Next, we have a database library that will do all the SQL heavy lifting work. This is based on PDO, so it should work with a lot other databases than just MySQL.

FunctionDescription
__constructThe constructor, which will automatically connect to the database when the object is created.
__destructThe destructor, which will automatically close the database connection when the object is destroyed.
execThis will run a single insert, replace, update, or delete query.
startAuto-commit off. Used in conjunction with end, when you have multiple queries to run.
endUsed in conjunction with start, commit or rollback all the previous queries.
fetchAllRun a select query, returns an associative array of with multiple rows of results.
fetchRun a select query, returns an associative array of column > value.
fetchColRun a select query, returns a flat array with values from the specified column.

SECTION D
PROCESS STEPS

Now that we have introduced all the necessary database tables and core library files, let us walk through the steps of a referral sales process.

STEP 1) CREATE REFERRAL ACCOUNTS

1-new-referral.php
exec(
  "INSERT INTO `referral` (`referral_name`, `referral_email`, `referral_password`) VALUES (?, ?, ?)",
  ["johndoe", "[email protected]", "123456"]
);
echo $pass ? "OK" : $libDB->error;

The first step of your referral system is to create a referral sign-up page… Which could be anything from a simple HTML form, to a complex manual screening process. You might also want to create an entire referral login portal for your partners.

STEP 2) GENERATE REFERRAL LINKS

2-referral-link.php
fetch(
  "SELECT * FROM `referral` WHERE `referral_id`=?",
  [$rID]
);

if (is_array($referral)) { 
  echo $url . "?ref=" . $referral['referral_name'];
} else {
  echo $url;
}

Next, we have to generate referral links for your partners to promote. This is as easy as pointing to a landing page with their referral login name placed in the query string – ?ref=REFERRAL NAME.

STEP 3) REFERRAL LINK LANDING PAGE

3-use-link.php
fetch(
    "SELECT * FROM `referral` WHERE `referral_name`=?",
    [$_GET['ref']]
  );
  if (is_array($referral)) {
    // We put the referral id into the session
    $_SESSION['ref'] = $referral['referral_id'];
  }
  // Redirect user to another page when done
  // This is to hide the referral link & stop users from messing with it
  header("Location: " . $redirect);
  die();
}
print_r($_SESSION);

So now, the customers will use the affiliate link and go to your specified landing page. There is not much trickery to this as well, just keep the referral ID in the session $_SESSION['ref'], so that we know this particular customer is introduced by that partner. Also, you might want to set some sort of timestamp or timeout – So that only orders within a set timeframe will be credited.

STEP 4) REFERRAL SALES

4-referral-sale.php
checkout() or something...
// Then calculate the own referral commission
$rID = $_SESSION['ref'];
$oID = 999;
$date = date("Y-m-d H:i:s");
$amount = 999.99;
$commission = 88.88;
$pass = $libDB->exec(
  "INSERT INTO `referral_sales` (`referral_id`, `order_id`, `order_date`, `order_amount`, `order_commission`) VALUES (?, ?, ?, ?, ?)",
  [$rID, $oID, $date, $amount, $commission]
);
echo $pass ? "OK" : $libDB->error;

// END THE REFERRAL SESSION IF YOU WANT
unset($_SESSION['ref']);

When the customer checks out the order, remember to give a commission to your partner. Pretty straightforward again – After processing the main order, proceed to calculate the commissions and put it into the referral sales table.

STEP 5) REPORTING

5-sales-report.php
fetchAll(
  "SELECT * FROM `referral_sales` WHERE `referral_id`=? AND `order_date` BETWEEN ? AND ?",
  [$rid, $start, $end], "order_id"
);
print_r($sales);

Well, the so-called final step is to generate monthly sales reports and send them to your partners… Plus their commissions.

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link as promised – Plus a small summary that may be useful to you.

NEW PROJECT?

Are you starting from scratch!? Things are going to get a little rough, and you will need to create a shopping cart plus a user system. Here are 2 of my other guides that might be able to help you:

3 Steps Simple PHP MYSQL Shopping Cart (Free Source Code)

4 Steps Simple PHP User Registration Form (With Email Verification)

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post 5 Steps Simple PHP Referral System appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

5 Steps Simple PHP Referral System

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×