PHPBuilder - A Practical Approach to Object-Relational Mapping in PHP Page 3



RSS Twitter
Articles Application Architecture

A Practical Approach to Object-Relational Mapping in PHP - Page 3

by: PHP Builder Staff
|
March 8, 2004

Now let's write Hippo::load() and Hippo::save(). (We're using the notation Hippo::load() to refer to the load method of Hippo. In this context, the notation has nothing to do with static methods.) Code for getting and setting properties, error checking, etc., has been omitted for simplicity.

<?php
//Hippo methods
function load($id
{
    
$this->id $id;
    
$conn mysql_connect('localhost''hippo_user''hippo_user');
    
mysql_select_db('hippos');
    
$result mysql_query("select name from hippos where id=$id");
    
$this->name mysql_result($result0'name');
    
application_utility_tasks();
}
function 
save() 
{
    
$conn mysql_connect('localhost''hippo_user''hippo_user');
    
mysql_select_db('hippos');
    if ( 
is_null($this->id) ) 
    {
        
//New record
        
$query "insert into hippos (name) values ('".$this->name."')";
        
mysql_query($query);
        
$this->id mysql_insert_id();
    }
    else 
    {
        
//Update existing record
        
$query "update hippos set name='".$this->name."' where id=".$this->id;
        
mysql_query($query);
    }
    
application_utility_tasks();
}
?>
In Hippo:load(), Line 3 copies the method's parameter into the id property. Lines 4 to 7 open the database and retrieve the name of a hippo. Hippo::save() uses the id property to determine whether an object represents a new hippo, or one that is already in the database (line 13). If the id is null, the method creates a new record. Otherwise, it updates an existing one. The call to the function application_utility_tasks()(lines 8 and 25) are just to remind us that we need to do these things somewhere.

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.