Sunday, February 26, 2012

Dynamic PHP user property creation based on database field names

Minimal code defining a workable user class/mini MVC. Upon creation, the SiteUser object defines public properties based off of database field names and data.

If you change anything about your database table (remove or add fields, change schema) the class will still create properties based on the current database table field names and values.

Another benefit is that you only need to hit the database for user data one time, when they're first logging in. All user data (first name, last name, etc.) is then stored in the session as part of the SiteUser object.


// connect to database
// ...


class SiteUser {
    function __construct($data) {
        $this->data = $data;

        // saves entire object as session variable
        // (maintains all user properties)
        $_SESSION['SiteUser'] = $this;
        // sets all properties of SiteUser based
        // on all field names from database
        foreach ($this->data as $key => $value) {
            $this->{$key} = $value;

    function __toString() {
        return json_encode($this->data);

    // other user functions, refer to properties
    // like '$this->userId' based on field names
    // from the database
    // ex.)
    function writeComment($text) {
        // a comments table with 3 fields, 
        // commentId (not null), posterId, and commentText
        $query = 'INSERT INTO comments VALUES(NULL, '
                          .$this->userId.', "'.$text.'");';

// get user ID from somewhere ...
$userId = 1;

$query = "SELECT * FROM userTable WHERE userId=$userId;";
$response = mysql_fetch_assoc(mysql_query($query));

$new_user = new SiteUser($response);

// prints out all user data in JSON
echo $new_user;

echo '<br><br>';

// access user's first name etc. (based on db field names)
echo $new_user->firstName;

// write new comment on behalf of user,
// get comment from somewhere
$comment = $_REQUEST['comment'];


No comments:

Post a Comment