Hippo::load()
and Hippo::save()
.(We’re using the notation
Hippo::load()
torefer 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($result, 0, '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();
}
?>
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 todetermine 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 thesethings somewhere.