MySQL
  Home arrow MySQL arrow Page 6 - Building a Simple Affiliate System in ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Building a Simple Affiliate System in PHP/MySQL
By: Roger Stringer
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 41
    2005-11-10

    Table of Contents:
  • Building a Simple Affiliate System in PHP/MySQL
  • Building The Database
  • Being Common
  • Your Index Page
  • Letting Affiliates Log in
  • Adding Affiliate Code to Your Site

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building a Simple Affiliate System in PHP/MySQL - Adding Affiliate Code to Your Site


    (Page 6 of 6 )

    There are two types of codes we have to set up for tracking affiliates.

    The first is called "click.php." This file is called when visitors click a link on an affiliate's website.

    <?
      include("common.php");

      if( $_REQUEST['refid'] ){
        $mykey = makeKey(10);
        SetCookie ("affid",$mykey);
        $_SESSION['affid'] = $mykey;
        mysql_query("UPDATE affiliates SET
    clicks=clicks+1 WHERE akey='".$_REQUEST['refid']."'",DBH);
        mysql_query("INSERT INTO affstats SET
    akey='".$_REQUEST['refid']."',type='1',
    OrderID='".$mykey."'",DBH);
      }
      header("Location: $redirecturl");
    ?>

    Now, create a file called "sale.php":

    <?
      include("common.php");

      $affid = $_SESSION['affid'];
      if (!$affid){
        $affid = $HTTP_COOKIE_VARS['affid'];
      }
      if (!$affid){
        exit;
      }else{
        mysql_query("UPDATE affstats SET
    type='2',price='{$affpay}',paid='0' where OrderID = '{$affid}'",DBH);
      } 
    ?>

    The file sale.php is called by adding it to your site like this:

      <img src="/affiliates/sale.php">

    Managing Affiliates

    Managing affiliates is important. We need to have a way to manage affiliates so we can set them as being paid, and perform other tasks. For the Affiliate management part, we will create five files.

    The first file is "accesscontrol.php." This file is similiar to login.php but works for the management area.

    <?php
      session_start();
      $auid = isset($_POST['auid']) ? $_POST['auid'] : $_SESSION['auid'];
      $pwd = isset($_POST['pwd']) ? $_POST['pwd'] :
    $_SESSION['pwd'];

      if(!isset($auid)) {
        loginform();
        exit;
      }
      if( $auid != $aduser || $pwd != $adpass ){
        unset($_SESSION['auid']);
        unset($_SESSION['pwd']);
        loginform();
        exit;
      }else if( $auid == $aduser && $pwd ==
    $adpass ){
        $_SESSION['auid'] = $auid;
        $_SESSION['pwd'] = $pwd;
      }
    ?>
    <?
      function loginform(){
        global $sitename;
    ?>
        <CENTER>
        <BR>
        <FONT FACE=verdana color=#FFFFFF
    size=5><B><?=$sitename?> Login</B></FONT>
        <BR>
        <TABLE cellspacing=0>
        <FORM method=post>
        <TR><TD>Username:
          <TD><INPUT type=text name=auid size=16>
        <TR><TD>Pass:
          <TD><INPUT type=pass name=pwd size=16>
        <TR><TD colspan=2><INPUT type=submit
    value="Log In >>"></TD>
        </FORM>
        </TABLE>
        <BR>
    <?
      }
    ?>

    Now, we create "manage.php":

    <?
      include("common.php");
      include("accesscontrol.php");
      include("header.php");
      $mode = isset($_REQUEST['mode']) ? $_REQUEST
    ['mode'] : '';
      switch($mode){
        case "stats":
          include("managestats.php");
          break;
        case "payout":
          include("payout.php");
          break;
        default:
          include("managemain.php");
          break;
      }
    ?>

    <?
      include("footer.php");
    ?>

    Next, we do "managemain.php":

    <p>Here are your affiliates, click on a username to view their stats.</p>
    <table border=1>
    <tr>
      <td>Username</td>
      <td>Password</td>
      <td>Email</td>
      <td>Affiliate Key</td>
    <?
      $results = mysql_query("SELECT *  FROM
    affiliates ORDER BY username;",DBH);
      while( $row = mysql_fetch_assoc($results) ){
        echo "<tr>";
        echo "<td><a href='manage.php?mode=stats&userId={$row['ID']}'>{$row
    ['username']}</a></td>";
        echo "<td>{$row['password']}</td>";
        echo "<td>{$row['email']}</td>";
        echo "<td>{$row['akey']}</td>";
        echo "</tr>";
      }
    ?>
    </table>

    The next file will be "managestats.php":

    <?
      $mystats = AffiliateStats($_GET['userId']);
      if($mystats['clicks'] > 0){
        $ratio = number_format( (($mystats
    ['orders'] / $mystats['clicks']) * 100), 2 )." %";
      }else{
        $ratio = "0 %";
      }
    ?>
    <b>Stats</b><br/>
    <table align=center width=350 border=1>
    <tr>
      <td>Total Clicks:</td>
      <td><?=number_format($mystats['clicks'],0)?>&nbsp;</td>
    </tr>
    <tr>
      <td>Total Orders:</td>
      <td><?=number_format($mystats['orders'],0)?>&nbsp;</td>
    </tr>
    <tr>
      <td>Ratio %:</td>
      <td><?=$ratio?>&nbsp;</td>
    </tr>
    </table>
    <br>
    <table align=center width=350 border=1>
    <tr>
      <td>Amount Earned:</td>
      <td>$<?=number_format($mystats['order_total'],2)?></td>
    </tr>
    <tr>
      <td>Payments Pending:</td>
      <td>$<?=number_format($mystats['pending_total'],2)?></td>
    </tr>
    <tr>
      <td>Amount Paid:</td>
      <td>$<?=number_format($mystats['paid_total'],2)?></td>
    </tr>
    </table>
    <?
      echo "<div align='center'><a
    href='manage.php?mode=payout&userId={$_GET
    ['userId']}'>Manage Payments</a></div>";
    ?>

    And finally, we create "payout.php":

    <?
      if($_GET['setaspaid']){
        mysql_query("UPDATE affstats SET paid='1'
    WHERE ID='{$_GET['setaspaid']}'",DBH);
      }
      if($_GET['setasunpaid']){
        mysql_query("UPDATE affstats SET paid='0'
    WHERE ID='{$_GET['setasunpaid']}'");
      }
      $sql = "SELECT * FROM affiliates WHERE
    ID='{$_GET['userId']}'";
      $lo = mysql_query( $sql );
      $affi = mysql_fetch_assoc($lo);
    ?>
    <?      if($affi['ptype']){       ?>
    Requested Payment Method: <?=( strtolower($affi
    ['ptype']) == "paypal" ? "PayPal" : "Check")?
    ><br>
    <?      }       ?>
    Payment Account: <?=( strtolower($affi
    ['ptype']) == "paypal" ? $affi['pemail'] :
    nl2br($affi['address']) )?><br>
    <br>
    <table align=center width=350 border=1>
    <?
      $q1 = "select * from affstats WHERE akey=
    '{$affi['akey']}' AND type=2 GROUP BY OrderID";
      $r1 = mysql_query($q1,DBH) or die(mysql_error());
      while($a1 = mysql_fetch_assoc($r1)){
    ?>
        <tr>
          <td>Amount Earned:</td>
          <td>$<?=$a1['price']?></td>
    <?                      if($a1[paid] == 1){     ?>
          <td><a href="manage.php?
    mode=payout&userId=<?=$_GET['userId']?
    >&setasunpaid=<?=$a1['ID']?>">Set As Not
    Paid</a></td>
    <?                      }else{  ?>
          <td><a href="manage.php?
    mode=payout&userId=<?=$_GET['userId']?
    >&setaspaid=<?=$a1['ID']?>">Set As
    Paid</a></td>
    <?                      }       ?>
        </tr>
    <?
      }
    ?>
    </table>

    Paying Your Affiliates

    I've given you an interface to use to see how much affiliates have made and set those earnings to paid, but you still have to pay them using the method they specify. If affiliates ask to be paid via check, then send them a check.

    One good practice is to set a minimum payment level, so that affiliates only get paid when they reach $20.00 or something like that.

    In Conclusion

    So, you now have a basic affiliate system. This can be made more complicated by modifying the code to allow banners, add more payout options, and so on. But I was aiming to give you something more simple to work with as a start.

    Affiliate systems can be very complex sometimes and this article was intended to give you a system that wasn't complex at all.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · When I saw the headline, I was quite anxious to read this article. Unfortunately,...
       · We are sorry to hear that you found the article disappointing. I am contacting the...
       · Well, The article is about building a simple affiliate system. Which is what it...
       · Hi. DevShed is all about open source programming. This article explores the...
       · This article was entirely appropriate. I mean if it was about inventory tracking...
       · Hello All, A big thanks to the author for taking time to write this...
       · There was a slight bad there when they inserted the article into the system...
       · Thanks! I'll let ya know how I make out!MrsDelley
       · and what is this:Parse error: parse error, unexpected ';' in...
       · sorry i am blind today, although it is an error.for those who may ask this Q...
       · one more Qurestion i have; What is this: <img src="/affiliates/sale.php">....
       · I keep getting this error message:Warning: mysql_query(): supplied argument is...
       · hi, first of all thanks for sharing this nice script. it seems to do exactly what i...
       · scrap my last comment, i should be logging into manage.php not accesscotrol.php....
       · Its a very nice script.:)Some notes from the comments that could be updated to...
       · I get the same exact error message. Could someone shed some light on the solution...
       · I get alot of these errors:Warning: mysql_query(): supplied argument is not a...
       · Hi There,this script in common.php:list($pending_total) = mysql_fetch_row(...
       · I have gone through each page and created all the files. Needless to say, there is a...
       · You access your MySQL database through a program called PHPMyAdmin. It should be...
       · Hi to the Poster above,I did eventually figure out how to upload the tables as...
     

       

    MYSQL ARTICLES

    - Take Some Load off MySQL with MemCached
    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...
    - Building a Search Engine with MySQL and PHP 5
    - Using Boolean Operators for Full Text and Bo...
    - PHP, MySQL and the PEAR Database
    - Working with PHP and MySQL
    - Getting PHP to Talk to MySQL
    - Creating an RSS Reader: the Reader
    - MySQL Security Overview
    - Creating the Admin Script for a PHP/MySQL Bl...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway