Webmaster Forum

Go Back   Webmaster Forum > Web Development > Coding Forum

Coding Forum Problems with your code? Discuss coding issues, including JavaScript, PHP & MySQL, HTML & CSS, Flash & ActionScript, and more.


Reply
 
LinkBack Thread Tools Display Modes
Old 01-31-2007, 01:47 AM   #1 (permalink)
Contributing Member
 
I like pie's Avatar
 
Join Date: 10-12-03
Location: California
Posts: 201
iTrader: 0 / 0%
Latest Blog:
None

I like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the rough
Send a message via ICQ to I like pie Send a message via AIM to I like pie Send a message via MSN to I like pie Send a message via Yahoo to I like pie
associative array vs object

I'm pretty new to OOP, and I've got a handle on the concept... but I'm still having trouble with actually using objects. I'm unsure if that's actually what I want in my current situation.

I'm re-writing an old game I made a few years back, and before what I would do to display a player's data on his "hq" page would be to query his id in the players table, and assign all that data to a $players[] array.

Now, I'm thinking it may be better to create a player object. But I'm not quite sure how to go about putting the info from a player's row in the db into the player object.

So far, this is what I have:

Code:
class player { var $username; var $last_login; function player($playerName, $playerLastLogin) { $this->username = $playerName; $this->last_login = $playerLastLogin; }
So... when i instantiate a player, I need to pass it those 2 values, but it seems really strange to pull those values from the db into a variable just to pass them along to an object variable...

Is this making any sense? I don't quite know how to gracefully populate a player object with data from the players table in the db. I know just using an array like before would work for now, but I'm sure a player object is the better way to go.
__________________
Foohon Pie Productions
I like pie is offline  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 02:00 AM   #2 (permalink)
Senior Member
 
Join Date: 01-02-07
Location: PA, USA
Posts: 191
iTrader: 0 / 0%
Latest Blog:
None

Arenlor is liked by somebodyArenlor is liked by somebodyArenlor is liked by somebodyArenlor is liked by somebody
Send a message via ICQ to Arenlor Send a message via AIM to Arenlor Send a message via MSN to Arenlor Send a message via Yahoo to Arenlor
I like arrays, I think they are better than objects. I started my programming career in C, then C++, then Java, now PHP, I love just using $arr = mysql_fetch_array($val); it's so useful. And way easier.
Arenlor is offline  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 02:14 AM   #3 (permalink)
Contributing Member
 
I like pie's Avatar
 
Join Date: 10-12-03
Location: California
Posts: 201
iTrader: 0 / 0%
Latest Blog:
None

I like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the rough
Send a message via ICQ to I like pie Send a message via AIM to I like pie Send a message via MSN to I like pie Send a message via Yahoo to I like pie
Yeah, that's what appealing to me right now. It seems so clean to just create an array to represent a row, which in turn represents a player's basic information.

But at the same time I really like the idea of having objects that not only represent something, but can also carry out tasks.

Although, I suppose I could easily enough write functions that take an array as a parameter.

Decisions... =/
__________________
Foohon Pie Productions
I like pie is offline  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 03:25 AM   #4 (permalink)
Moderator
 
Hades's Avatar
 
Join Date: 01-23-07
Location: Buenos Aires, Argentina
Posts: 1,187
iTrader: 0 / 0%
Hades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest order
You can write a small script to automatically create objects from the results of a database query.

I have a database wrapper which I wrote for PHP and works like a recordset. Besides, I create classes to represent entities.

My class looks like this:

PHP Code:

class Player{

  function 
get($filters){
     
$sql "SELECT... from player ";
     if (
$filters$sql .= "WHERE " $filters;
     
$rData SQL::query($sql);
     return(
$rData);
  }



Then my frontend code looks like this:

PHP Code:

$rData 
Player::get("name LIKE 'Cris%'");

for(
$i=0;$i<$rData->quantity();$i++){
   echo( 
$rData->field("name",$i) . "<br/>" );


I used 3 classes there:
Class Player, which represents the player entity.
Class SQL, that acts like a database wrapper.
Class Data, that works like a recordset to manage the data.

I can post the code of these classes if you want. Let me know!
__________________
Hades,
Ancient god, King of the Nether World, and Guardian of the Dead.
...and on my free time I'm also a web developer, contact me if you need one!
Hades is online now  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 11:25 AM   #5 (permalink)
Contributing Member
 
I like pie's Avatar
 
Join Date: 10-12-03
Location: California
Posts: 201
iTrader: 0 / 0%
Latest Blog:
None

I like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the rough
Send a message via ICQ to I like pie Send a message via AIM to I like pie Send a message via MSN to I like pie Send a message via Yahoo to I like pie
It would be helpful if you could. =) I've got the idea of what you're saying, but I wouldn't know how to start implementing it.
__________________
Foohon Pie Productions
I like pie is offline  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 06:59 PM   #6 (permalink)
Moderator
 
Hades's Avatar
 
Join Date: 01-23-07
Location: Buenos Aires, Argentina
Posts: 1,187
iTrader: 0 / 0%
Hades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest orderHades is a web professional of the highest order
OK, here we go...

First, you have three files, one that acts like a database connector, another that acts as a dataaccess wrapper and the last one will work as a recordset.

Database.php
PHP Code:

class Database{
        function 
connect$hostname$user$password$db )
        {
            static 
$connected;
            
            if (
$connected) return;
            
            
$connId = @mysql_connect($hostname$user$password) or die('Cannot connect to database server');
            @
mysql_select_db($db) or die('The database is currently down');
            
$connected true;
            return 
$connId;
        }
        function 
close(){
            
mysql_close();
            return;
        }

SQL.php
PHP Code:
class SQL {
    
    
/**
     * @desc executes a single DDL query
     *
     * @param string $sql
     * @param integer $queryType
     * @param integer-pointer $id
     * @param string-pointer $error
     * @return $result
     */
    
function execute($sql$queryType, &$id,&$error,$log=true)
    {
        
Database::connect("host","username""password""database");
                
        
$sqlTransact $sql;
        
$result mysql_query($sql);
        if(
$queryType=="DBINSERT"
        {
            
$id = @mysql_insert_id();
        }
        
        if (
mysql_errno()){
            
$error mysql_error()."\nQuery: " $sql;
        }
        
        
Database::close();
        return 
$result;
    }
    
    
    
/**
     * @desc executes a single DML query
     *
     * @param string $sql
     * @return Data $rs
     */
    
function query($sql)
    {
        
Database::connect($_SESSION['sess_conf']['db_hostname'],$_SESSION['sess_conf']['db_username'], $_SESSION['sess_conf']['db_password'], $_SESSION['sess_conf']['db_database']);
        
$rs =  mysql_query($sql) or die(mysql_error() . "<br><b>QUERY</b>:<br>" nl2br($sql));
        if(
mysql_num_rows($rs) >0)
        {
            for(
$i=0$imysql_num_fields($rs); $i++)
                
$fields[mysql_field_name($rs$i)] = $i;

            while (
$row mysql_fetch_row($rs))
                
$vec[] = $row;

            
mysql_free_result($rs);
            
Database::close();
            return new 
Data($fields$vec);
        }
        
Database::close();
        return new 
Data();
    }
    

Data.php
PHP Code:
class Data {
    
    var 
$_fields "";
    var 
$_data  "";
    
    function 
Data($_fields=Array(), $_data=Array())
    {
        
$this->_fields $_fields;
        
$this->_data = &$_data;
    }
    
    
/**
     * count the result
     *
     * @return int
     */
    
function quantity() {
        return 
count($this->_data);
    }
    
    
/**
     * count columns
     *
     * @return int
     */
    
function quantityFields() {
        return 
count($this->_fields);
    }
    
    
/**
     * get the Field
     * 
     * @param String $field
     * @param int $row
     * 
     * @return mixed
     */    
    
function field($field$row)
    {
        
$value $this->_data[$row][$this->_fields[$field]];
        return 
$value;
    }
    
    
/**
     * get the colum name
     * 
     * @param String $fieldCol
     * 
     * @return String
     */
    
function fieldNameByPosition($fieldCol)
    {
        
$aFields array_keys($this->_fields);
        return 
$aFields[$fieldCol];
    }
    
    
/**
     * get the field position by name
     *
     * @param String $name
     * @return int
     */
    
function getFieldPositionByName($name)    {
        
        if (!
array_key_exists($name$this->_fields)) {
            return 
false;
        }
        
        return 
$this->_fields[$name];
    }
    
    
/**
     * get the Field
     * 
     * @param int $field
     * @param int $row
     * 
     * @return mixed
     */
    
function fieldByPosition($field$row)
    {
        
$value $this->_data[$row][$field];
        return 
$value;
    }
    
    
/**
     * make an array.
     *
     * @return Array
     */
    
function &getArray(){
        
$aResponse = array();
        
$keys array_keys($this->_fields);
        
        for(
$i=0;$i<count($this->_data);$i++){
            
$aResponse[$i] = array();
            foreach(
$keys as $k){
                
$aResponse[$i][$k] = $this->_data[$i][$this->_fields[$k]];
            }
        }
        return (
$aResponse);
    }
    
    
    function 
getColsNames()    {
        
        return 
array_keys($this->_fields);
    }
    
    


Then, you will have a class for each entity in your system, if you need a Player entity, my class looks like the one as follows:

Player.php
PHP Code:
/**
 *    Class Player
 *    Class for player management
 *    
 *    Related Table: player
 *    Alias: pl
 *    ID: idPlayer
 *    Label: name
 *    Relative Path:  
 *    
 *    Author: Chris @ Liberty Web Systems
 *    Date: Wed Jan 31 22:38:39 ART 2007
**/
class Player {
    
    
/**
     * Returns a filtered list from player (pl)...
     *
     * @param integer $id
     * @param string $filters
     * @param string $order
     * @param string $limit
     * @return Data
     */
    
function get($id="",$filters="",$order="",$limit=""){
        global 
$_SYS;
        
$sql "
        SELECT 
            pl.idPlayer,
            pl.* 
        FROM player pl
        WHERE 1
        "
;
        if (
$id$sql .= " AND pl.idPlayer = '".$id."'";
        if (
$filters$sql .= "AND " $filters;
        if (
$order$sql .= " ORDER BY " $order;
        if (
$limit$sql .= " LIMIT $limit";
        
        
$rData SQL::query($sql);
        return (
$rData);
    }
    
    
/**
     * Returns the count of registries from a filtered list
     *
     * @param integer $id
     * @param string $filters
     * @return integer
     */
    
function countRegistries($id="",$filters=""){
        global 
$_SYS;
        
$sql " SELECT COUNT(pl.idPlayer) as cnt FROM player pl WHERE 1 ";
        if (
$id$sql .= " AND idPlayer = '".$id."' ";
        if (
$filters$sql .= " AND " $filters;
        
        
$rData SQL::query($sql);
        return (
$rData->field("cnt",0));
    }
    
    
    
/**
     * Inserts a new registry into player
     *
     * @param array $aData
     * @return integer
     */
    
function insert($aData){
        
        
        
$sql "
        INSERT INTO player
        (
            name,
            dateAdded,
            team,
            points
        )
        VALUES
        (
            '"
.$aData['name']."',
            '"
.$aData['dateAdded']."',
            '"
.$aData['team']."',
            '"
.$aData['points']."'
        )
        "
;
        
SQL::execute($sql,DBINSERT,$id,$error);
        return(
$id);
    }
    
    
/**
     * Modifies a registry from player
     *
     * @param integer $id
     * @param array $aData
     * @return integer
     */
    
function update($id,$aData){
        
        
$sql "
        UPDATE player SET
            
            name = '"
.$aData['name']."',
            dateAdded = '"
.$aData['dateAdded']."',
            team = '"
.$aData['team']."',
            points = '"
.$aData['points']."'
        WHERE idPlayer = '"
.$id."'";
        
        
SQL::execute($sql,"DBUPDATE",$id,$error);
    
    }
    
    
/**
     * Deletes a registry from player
     *
     * @param integer $id
     */
    
function delete($id){
        global 
$_SYS;
        
$sql "DELETE FROM player WHERE idPlayer = $id";
        
SQL::execute($sql,"DBDELETE",$id,$error);
    }
    
    

After including these files one can start programming (okok that was a joke!)

Lets suppose that you need to display a list of players, you can do something like this:

PHP Code:
include("Database.php");
include(
"SQL.php");
include(
"Data.php");
include(
"Player.php");

//Dummy Data.
$idPlayer 1;

//a simple, "select all" query.
$rDataAll Player::get();

//select only one player.
$rDataOnlyOne Player::get($idPlayer);

//select by filter
$rDataFiltered Player::get(false," points > '100'");

/*FOR FURTHER INFORMATION ON HOW TO USE THE GET FUNCTION, READ ITS PROTOTYPE ON THE PLAYER CLASS*/ 
Now you have three recordsets, you can read them with this code

PHP Code:
for($i=0;$i<$rDataAll->quantity();$i++){
    echo(
"
    Name = "
.$rDataAll->field("name",$i)." <br/>
    Added = "
.$rDataAll->field("dateAdded",$i)." <br/>
    Team = "
.$rDataAll->field("team",$i)." <br/>
    Points = "
.$rDataAll->field("points",$i)." <br/>
    <hr/>
    "
);


To insert a registry into the player table, you can use this code:
PHP Code:
$aData = array(
 
"name"=>"Jack",
 
"dateAdded"=>"2007-01-01",
 
"team"=>"blue",
 
"points"=>1000
);

Player::insert($aData); 
You can do something similar in order to update and delete registries, take a look at the prototypes of the Player class (documentation is very useful )

This is how I work, however, any suggestion will be accepted. Post your questions if you need any kind of help, we are all here to learn!
__________________
Hades,
Ancient god, King of the Nether World, and Guardian of the Dead.
...and on my free time I'm also a web developer, contact me if you need one!
Hades is online now  
Add Post to del.icio.us
Reply With Quote
Old 01-31-2007, 07:56 PM   #7 (permalink)
Contributing Member
 
I like pie's Avatar
 
Join Date: 10-12-03
Location: California
Posts: 201
iTrader: 0 / 0%
Latest Blog:
None

I like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the roughI like pie is a jewel in the rough
Send a message via ICQ to I like pie Send a message via AIM to I like pie Send a message via MSN to I like pie Send a message via Yahoo to I like pie
Well holy crap. That's quite... pretty

Thanks a ton, I'm gonna play around with all that to get a feel for how it all works. I'm pretty impressed, that's rather clean code you've got there
__________________
Foohon Pie Productions
I like pie is offline  
Add Post to del.icio.us
Reply With Quote
Go Back   Webmaster Forum > Web Development > Coding Forum

Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
array weirdness in php I like pie Coding Forum 7 01-27-2007 12:36 AM
imploding array keys I like pie Coding Forum 7 12-28-2006 05:55 PM
quick array question I like pie Coding Forum 1 12-02-2006 10:05 PM
Adding 1 to array? spl1nter Coding Forum 4 09-14-2004 08:22 PM
<object> </object> area clickable softstor Coding Forum 3 06-14-2004 12:35 PM


Sponsor Links
Get exposure! Contextual Links V7N SEO Blog V7N Directory


All times are GMT -7. The time now is 04:51 PM.
© Copyright 2008 V7 Inc
Powered by vBulletin
Copyright © 2000-2009 Jelsoft Enterprises Limited.


Search Engine Optimization by vBSEO 3.3.0 ©2009, Crawlability, Inc.