Iterator Implementation

Iterator Implementation Task
Create a Locations class that implements PHP’s Iterator interface. The class will iterate over all rows in a table named locations (outlined below) and return the id and name in a key=>value form. The class must be used as it is in the Usage section below.
Assumptions
• A database connection has already been set up for you. Just use mysql_query for your queries.
• Data already exists in the table.
Table Structure
±--------------------±------------±-----±----±--------±---------------+
| Field | Type | Null | Key | Default | Extra |
±--------------------±------------±-----±----±--------±---------------+
| location_id | int(11) | NO | PRI | NULL | auto_increment |
| location_name | varchar(32) | YES | | NULL | | ±--------------------±------------±-----±----±--------±---------------+
Usage
echo ‘

    ’; foreach (new Locations as $id => $name) {
    printf(’
  • %s
  • ’, $id, $name); echo ‘
’;
}

Hi Jim :smiley:

I replied to your email and sent the code, but i’ve included it here too:
[php]class Locations
{
function locations()
{
$query = “SELECT * FROM locations ORDER BY location_id ASC”;
$result = mysql_query($query);

	while($row = mysql_fetch_array($result, MYSQL_NUM))
	{
		$data[] = array('location_id' => $row[0], 'location_name' => $row[1]);
	}
	return $data;
}

}

$x = new Locations;
$data = $x->locations();
$count = count($data);

echo ‘

’;
[/php]

Goodluck with your course
:wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service