My 1st fully functional class.

Place to place any code snippets, completed games, or even uncompleted games for IR users to use.
Post Reply
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

My 1st fully functional class.

Post by Torniquet »

I wrote this class a week or so ago just to practice. It is probably a pretty useless class, but here it is anyway :)

user.class.php

Code: Select all

<?php

// User class


class user{
    
    private $id = 0;
    private $pass = "";
    
    private $table;
    private $id_field;
    private $password_field;
    private $db;
    
    function __construct($db, $table = "user_table", $id_field = "id", $password_field = "password")
    {
        $this->table = $table;
        $this->id_field = $id_field;
        $this->password_field = $password_field;
        $this->db = $db;
    }
    
    // SET USER ID AND PASS
    function load_user($id, $pass)
    {
        $this->id = $id;
        $this->pass = $pass;
    }
    
    
    //  USER LOGIN
    function user_login($data, $stay_logged = false)
    {
        //global $this->db;
        
        $last = end($data);
        
        $query = "SELECT `{$this->id_field}`, `{$this->password_field}` FROM `{$this->table}` WHERE ";
        
        foreach($data as $k => $v)
        {
            $query .= "`{$k}`='{$v}'";
            if($v != $last)
            {
                $query .= " AND ";
            }
        }
        
        $query .= " LIMIT 1";
        
        $sql = $this->db->query($query);
        
        if($sql->num_rows > 0)
        {
            $row = $sql->fetch_object();
            $this->load_user($row->{$this->id_field}, $row->{$this->password_field});
            return true;
        }
        else
        {
            return false;
        }
        
    }
    
    
    //FETCH SPECIFIED USER DATA
    function fetch_user_data($data)
    {
        //global $this->db;
        
        $last = end($data);
        $query = "SELECT ";
        
        foreach($data as $v)
        {
            $query .= "`{$v}`";
            if($v != $last)
            {
                $query .= ", ";
            }
        }
        
        $query .= " FROM `{$this->table}` WHERE `{$this->id_field}`={$this->id} AND `{$this->password_field}`='{$this->pass}' LIMIT 1";
        $sql = $this->db->query($query);
        
        return $sql->fetch_object();
    }
    
    // AUTHENTICATE USER WITH ID AND PASSWORD
    function auth()
    {
        //global $this->db;
        $query = "SELECT `{$this->id_field}` FROM `{$this->table}` WHERE `{$this->id_field}`={$this->id} AND `{$this->password_field}`='{$this->pass}' LIMIT 1";
        $sql = $this->db->query($query);
        
        if($sql->num_rows > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    // OUTPUT LOGIN FORM
    function load_form($template)
    {
        echo file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/templates/{$template}");
    }
    
    
    // REGISTER NEW USER
    
    function register_user($data)
    {
        //global $this->db;
        $query = "INSERT INTO `{$this->table}` SET ";
        $last = end($data);
        
        foreach($data as $k => $v)
        {
            $query .= "`{$k}`='{$v}'";
            if($v != $last)
            {
                $query .= ", ";
            }
        }
        
        $this->db->query($query);
        
    }
    
    // AUTHENTICATE DATA
    function auth_data($data)
    {
        //global $this->db;
        
        $query = "SELECT `{$this->id_field}` FROM `{$this->table}` WHERE ";
        
        $last = end($data);
        
        foreach($data as $k => $v)
        {
            $query .= "`{$k}`='{$v}'";
            if($v != $last)
            {
                $query .= " AND ";
            }
        }
        
        $query .= " LIMIT 1";
        
        $sql = $this->db->query($query);
        
        if($sql->num_rows > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
        
    }
    
}

?>

the class is designed to work with mysqli objects (so knowing how to initiate a mysqli object instance helps).

The construct has 1 required attribute and 3 optional. The 1st one is the mysqli database connection variable. This is needed
The second is the name of the user table which defaults to user_table.
The third is the user id field. This defaults to id.
the fourth is the password field, which defaults to password.

once the new class instance is initiated, you will need to load certain information into the class. The information required is the user id and the user password. You can keep these set in sessions.

Code: Select all

$user->load_user($_SESSION['uid'], $_SESSION['upass']);
 
Following on from that, you authorise the user. you can either set it into a new variable or call it every time a user's authenticity is required.

Code: Select all

$auth = $user->auth();

// or

if($user->auth() === true)
 
the auth() function returns true or false using the loaded id and password.


But it doesn't stop there!

You can also select certain information from the user database by using an array and the fetch_user_data function

Code: Select all

$data = array('name', 'age', 'job');
$info = $user->fetch_user_data($data);

//call information like so

echo $info->name;

if($info->age > 30)

echo 'My job is ', $info->job;
 

So it loads a user, authenticates a user and calls user information... What about logging in a user? Yes it does that too...

Code: Select all

if(isset($_POST['submit']))
{
    $data = array(
        "email" => $_POST['email'],
        "password" => md5($_POST['password'])
    );

    $user->user_login($data);
}
 
using an array, you target specific fields and check information contained against the keys. in this case, we are logging in a user using their email and password. parsing information for security is not included! this is to be done by you.

it even registers users.....

in the same fashion as logging in, you set the fields and data into an array which you want to put into the database.

Code: Select all

$data = array(
"username" => $_POST['username'],
"password" => $_POST['password'],
"age" => $_POST['age']
);

$user->register_user($data);
 

And finally, it checks to see if data is already input into the table.

Code: Select all

$data = array(
"username" => $_POST['username']
);

if($user->auth_data($data) === true)
{
    // Data already exists in the table!
}
 

Well i think that is all lol. Hope its of some use to someone :)
New Site Coming Soon! Stay tuned :D
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: My 1st fully functional class.

Post by hallsofvallhalla »

very kewl man!
Zettiee
Posts: 17
Joined: Wed Oct 12, 2011 8:13 am

Re: My 1st fully functional class.

Post by Zettiee »

Nice work.
You should try out mysqli (its not much different just a little more secure =])
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: My 1st fully functional class.

Post by Torniquet »

Torniquet wrote:
the class is designed to work with mysqli objects (so knowing how to initiate a mysqli object instance helps).
already 1 step ahead of you :p

I only every use mysqli now.
New Site Coming Soon! Stay tuned :D
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: My 1st fully functional class.

Post by Jackolantern »

mysqli4life
The indelible lord of tl;dr
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: My 1st fully functional class.

Post by Xaleph »

PG for life bro!

But anyway, MySQL works awesome, the PDO in mysqli works as well, so MySQL is a damn good db driver for regular web applications. However, PG is Ruler and master in the OS DB driver world.
metacatdud
Posts: 19
Joined: Fri Sep 30, 2011 8:20 am

Re: My 1st fully functional class.

Post by metacatdud »

Well classes are awesome and more time efficient once you build them. They will show their potential when your application will get bigger
Below is a step by step PDO usage tut:
Beware!!! Is a big one. Enough chatter, let's code!
Before start make sure you have php5.1 (5.3 recommended [many bug fixes to PDO API ])

1) First we need the to write a driver name it SqlPdoDriver.php

Code: Select all

<?php

class SqlPdoDriver 
{
    var $dbHost = "localhost";
    var $dbPort = "";
    var $dbName = "test";
    var $dbUser = "root";
    var $dbPass = "root";
    
    var $dbHandler;
    
    public function __construct() 
    {
        if($this->dbPort=="")
        {
            $dsnString = "mysql:host=$this->dbHost;dbname=$this->dbName";
        }
        else
        {
            $dsnString = "mysql:host=$this->dbHost;port=$this->dbPort;dbname=$this->dbName";
        }
        
        try
        {
            $this->dbHandler = new PDO($dsnString, $this->dbUser, $this->dbPass);
            $this->dbHandler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }
        catch (PDOException $e)
        {
            die($e->getMessage());
        }
    }
}

?>
2) Change these to mach your needs

Code: Select all

var $dbHost = "localhost";
    var $dbPort = "";
    var $dbName = "test";
    var $dbUser = "root";
    var $dbPass = "root";
To test to see if the above is working add

Code: Select all

var_dump(new SqlPdoDriver());
before

Code: Select all

?>
You should see something like

Code: Select all

object(SqlPdoDriver)[1]
  public 'dbHost' => string 'localhost' (length=9)
  public 'dbPort' => string '' (length=0)
  public 'dbName' => string 'test' (length=4)
  public 'dbUser' => string 'root' (length=4)
  public 'dbPass' => string 'root' (length=4)
  public 'dbHandler' => 
    object(PDO)[2]
If everyhing is ok remove the var_dump line.

Now create a file called users.php. This will be our future model that will handle our users

It looks something like below

Code: Select all

<?php
require_once ('sqlPdoDriver.php');

/*
 * A standard MVC Class
 * 
 * This is a Model for the user
 * You can add more properties and methods as you need
 * 
 */

class Users 
{
    static $tableName = "test_table";
    public $tableFields = "name,email";
    public $tableObject = array();

    private $dbObj;

    public $id = "";
    public $name = "";
    public $email = "";
    
    
    public function __construct($array=array()) 
    {
        $this->dbObj = new SqlPdoDriver();
        $this->tableObject = $array;
    }

    //A select function
    public function GetUser()
    {
        $query = $this->dbObj->dbHandler->prepare("SELECT ".$this->tableFields." FROM ".Users::$tableName." WHERE id = :select OR email = :select");
        $query->execute($this->tableObject);
        $query->setFetchMode(PDO::FETCH_OBJ);  
        return $query;
    }
    
    //A multiselect
    public function GetUserList()
    {
        $query = $this->dbObj->dbHandler->prepare("SELECT ".$this->tableFields." FROM ".Users::$tableName."");
        $query->execute();
        $query->setFetchMode(PDO::FETCH_OBJ);  
        
        return $query;
    }

        //An insert function
    public function AddUser()
    {
        $query = $this->dbObj->dbHandler->prepare("INSERT INTO ".Users::$tableName." (".$this->tableFields.") VALUE (:name,:email)");
        $query->execute($this->tableObject);
        
        //A closing handler
        $this->dbObj->dbHandler = NULL;
    }

    //A delete function
    public function DeleteUser()
    {
        $query = $this->dbObj->dbHandler->prepare("DELETE FROM ".Users::$tableName." WHERE id = :delete OR email = :delete");
        $query->execute($this->tableObject);
        

        //A closing handler
        $this->dbObj->dbHandler = NULL;
    }
    
}
?>

The functions do what their name say. I want to stop upon the properties and see what they do
- This is the table name

Code: Select all

    static $tableName = "test_table"; 
- This are the fields of my table. You can add as how many you want

Code: Select all

public $tableFields = "name,email"; 
- Now this baby is our data selector. It's an array and you can load it with some data as log as it is valid. I will come back to it.

Code: Select all

public $tableObject = array();


- This is de PDO driver handler

Code: Select all

private $dbObj;
- These are tables fields

Code: Select all

public $id = "";
public $name = "";
public $email = "";
And now, time for some magic. Create an index.php to play with

First let's load the users class

Code: Select all

require_once ('users.php');
Now create these arrays

Code: Select all

$insertArray = array('name'=>'Test user','email'=>'test@test.com');
$deleteArray = array('delete'=>'Test user');
$selectArray = array('select'=>'test@test.com');
These arrays above will build our data selector the one called $tableObject from users class.

Now we're all set to do some things such as add,delete,select
- Add a user to database

Code: Select all

$user = new Users($insertArray);
$user->AddUser();
The record with name: Test user and email: test@test.com should be in the database

If you look into the insert array you will found an associative array. As you probablly notice the keys are the column names. But there the hell delete and select keys, from other array, came from. Well take a look at GetUser function and DeleteUser from Users class. They are the defined "Placeholder" for the queries.
I really recommend to use Named placeholders. You will allways know who do what

Now let's delete

Code: Select all

$user = new Users($deleteArray );
$user->DeleteUser();
To select, well we need some data because now should be empty. If is not empty let's select
- One record

Code: Select all

$user = new Users($selectArray);
$userData = $user->GetUser()->fetch();  //This will retrun an Object
To get the data we need from $userData we do like so

Code: Select all

$name  = $userData->name;
- Select entire table

Code: Select all

$user = new Users();
$userList = $user->GetUserList()->fetchAll();
You notice that the user is takeing no array (data selector). Well we don't need it. Now you see how you can use a constructor in many ways C# style. To parse the array above loop through it with a foreach or what ever you want

Code: Select all

foreach ($userList as $key => $value) 
{
    echo $value->name . " - ".$value->email;   
}
Now you will see some OR operator into the functions into the Users class. You can remove them and create separate calls for each selector.

If you have any questions and you will have post them here.
Good luck!
Post Reply

Return to “Code Sharing”