How to access data in database then return them as Object.
Posted: Sun Nov 12, 2006 6:39 am
Hello folks,
I have a question which I am wondering myself about returning object from database. Could you help me out ?
Is this the right way to return object from the database ? Or there is simpler way in doing this ?
Thank you,
Chris
I have a question which I am wondering myself about returning object from database. Could you help me out ?
Is this the right way to return object from the database ? Or there is simpler way in doing this ?
Code: Select all
<?php
require_once ('class.MySQLConnection.php');
require_once ('class.Address.php');
class UserFactory {
/**
* Method that retrieve all addresses that a user has
* @name getAddressesForUser
* @param int $userID
* @return Array
*/
public static function getAddressesForUser($userID) {
$query = "SELECT * FROM tbladdress WHERE userID = $userID";
$addresses = array();
$result = mysqli_query(MySQLConnection::connectToMySQL(), $query);
if (!$result) {
die ("Failed getting addresses for user: $userID");
}
if (!mysqli_num_rows($result)) {
die ("You haven't specified any addresses yet.");
}
for ($i = 0; $i < mysqli_num_rows($result); $i++) {
//allocate data to private vars for each address class
foreach (mysqli_fetch_assoc($result) as $key => $value) {
switch ($key) {
case "addressID":
$objAddress = new Address ($value);
case "typeID":
$objAddress->setAddressType($value);
case "streetAddress":
$objAddress->setStreetAddress($value);
case "state":
$objAddress->setState($value);
case "city":
$objAddress->setCity($value);
case "postalCode":
$objAddress->setPostalCode($value);
case "country":
$objAddress->setCountry($value);
case "defaultAddress":
$objAddress->setDefaultAddress($value);
case "addedOn":
$objAddress->setAddedOn($value);
case "lastUpdatedOn":
$objAddress->setLastUpdatedOn($value);
}
}
$addresses[] = $objAddress;
}
return $addresses;
mysqli_close(MySQLConnection::connectToMySQL());
}
}
?>Chris