Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > PHP/MySQL > BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1
Password Reminder
Register
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1
This is the forum to discuss the Wrox book Professional PHP5 by Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove; ISBN: 9780764572821
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional PHP 5 ISBN: 978-0-7645-7282-1 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
 
 
Thread Tools Display Modes
  #1 (permalink)  
Old March 27th, 2013, 08:41 AM
Registered User
Points: 69, Level: 1
Points: 69, Level: 1 Points: 69, Level: 1 Points: 69, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2013
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Default Chapter03 - Putting Objects to Work

Hey authors, I need your help!

I am creating my own PHP5 application and I figure out that my objects of type 'User' don't return their fields of table using method toString. Why is it happen? Why? The server can create objects, in this case, 4 objects of type 'User' but can't return your data.

You are free copy the next code and test in your server.

Class PropertyObject
Code:
<?php
require_once('interface.Validator.php');

abstract class PropertyObject implements Validator{
	
	protected $propertyTable = array();
	protected $changedProperties = array();
	protected $data;
	protected $errors = array();
	
	public function __construct($arData){
		$this->data = $arData;
	}
	
	function __get($propertyName){
		if(!array_key_exists($propertyName,$this->propertyTable))
			throw new Exception("Invalid property \"$propertyName\"!");
			
		if(method_exists($this,'get'.$propertyName)){
			return call_user_func(array($this,'get'.$propertyName));
		}else{
			return $this->data[$this->propertyTable[$propertyName]];
		}
	}
	
	function __set($propertyName,$value){
		if(!array_key_exists($propertyName,$this->propertyTable))
			throw new Exception("Invalid property \"$propertyName\"!");
			
		if(method_exists($this,'set'.$propertyName)){
			return call_user_func(array($this,'set'.$propertyName),$value);
		}else{
			if($this->propertyTable[$propertyName] != $value && !in_array($propertyName,$this->changedProperties)){
				$this->changedProperties[]=$propertyName;
			}
				$this->data[$this->propertyTable[$propertyName]] = $value;
		}
	}
	
	function validate(){
		
	}
}
?>
Class User
Code:
<?php
require_once('class.PropertyObject.php');

class User extends PropertyObject{
	
	function __construct($userid){
		$arData = DataManager::getUserData($userid);
		
		parent::__construct($arData);
		
		$this->propertyTable['userid']='userid';
		$this->propertyTable['id']='userid';
		$this->propertyTable['email']='semail';
		$this->propertyTable['password']='spassword';
	}
	
	function validate(){
		if(strlen($this->password)<4){
			$this->errors['password'] = 'O tamanho da password deve ser superior a 4 caracteres!';
		}
		
		if(!filter_var($this->email, FILTER_VALIDATE_EMAIL)){
			$this->errors['email'] = 'Este $this->email n&atilde;o &eacute; v&aacute;lido!';
		}
		
		if(sizeof($this->errors)){
			return false;
		}else{
			return true;
		}
	}
	
	function __toString(){
		return $this->id.' '.$this->email.' '.$this->password;
	}
}
?>
Class DataManager
Code:
<?php
require_once('class.User.php');

class DataManager{
	
	private static function _getConnection(){
		static $hDB;
		
		if(isset($hDB)){
			return $hDB;
		}
		
		$hDB = new mysqli('hostname','username','password','dbname');
		if(mysqli_connect_error()){
			die('Failure connecting to the database! Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
		}
		//debug
		//echo 'Success... ' . mysqli_get_host_info($hDB) . "\n";
		return $hDB;
	}
	
	public static function getAllUsersAsObjects(){
		$sql = "SELECT * FROM user;";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!$res){
			die("Falhou ao obter todos utilizadores da aplicação");
		}
		if(mysqli_num_rows($res)){
			$objs=array();
			while($row = mysqli_fetch_assoc($res)){
				$objs[] = new User($row['id']);
			}
			return $objs;
		}else{
			return array();
		}
	}
	
	public static function getUserData($userid){
		$sql = "SELECT * FROM user WHERE id='".$userid."';";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!($res && mysqli_num_rows($res))){
			die("Falhou ao obter dados sobre a data do utilizador $userid!");
		}
		return mysqli_fetch_assoc($res);
	}
}
?>
test.php
Code:
<?php
require_once('class.DataManager.php');

function println($data){
	print $data."<br>\n";
}

$arUsers = DataManager::getAllUsersAsObjects();
/*echo "<pre>";
var_dump($arUsers);
echo "</pre>";*/

foreach($arUsers as $objEntity){
	if(get_class($objEntity) == 'User'){
		 print "<h1>User - {$objEntity->__toString()}</h1>";
	}
}
?>
SQL
Code:
create table user(
id int auto_increment,
email varchar(255) not null default '',
password varchar(255) not null default '',
primary key(id)
)engine=innodb;

insert into user(email,password) values ("user1@email.com" ,"user1"),("user2@email.com","user2"),("user3@email.com","user3"),("user4@email.com","user4");
  #2 (permalink)  
Old March 28th, 2013, 11:30 AM
Registered User
Points: 69, Level: 1
Points: 69, Level: 1 Points: 69, Level: 1 Points: 69, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2013
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Default

My SQL script and DataManager are wrong because the name of fields from SQL don't match name of fields from class (see Class User).


Wrong DataManager
Code:
<?php
require_once('class.User.php');

class DataManager{
	
	private static function _getConnection(){
		static $hDB;
		
		if(isset($hDB)){
			return $hDB;
		}
		
		$hDB = new mysqli('hostname','username','password','dbname');
		if(mysqli_connect_error()){
			die('Failure connecting to the database! Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
		}
		//debug
		//echo 'Success... ' . mysqli_get_host_info($hDB) . "\n";
		return $hDB;
	}
	
	public static function getAllUsersAsObjects(){
		$sql = "SELECT * FROM user;";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!$res){
			die("Falhou ao obter todos utilizadores da aplicação");
		}
		if(mysqli_num_rows($res)){
			$objs=array();
			while($row = mysqli_fetch_assoc($res)){
				$objs[] = new User($row['id']);
			}
			return $objs;
		}else{
			return array();
		}
	}
	
	public static function getUserData($userid){
		$sql = "SELECT * FROM user WHERE id='".$userid."';";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!($res && mysqli_num_rows($res))){
			die("Falhou ao obter dados sobre a data do utilizador $userid!");
		}
		return mysqli_fetch_assoc($res);
	}
}
?>
Correct DataManager
Code:
<?php
require_once('class.User.php');

class DataManager{
	
	private static function _getConnection(){
		static $hDB;
		
		if(isset($hDB)){
			return $hDB;
		}
		
		$hDB = new mysqli('hostname','username','password','dbname');
		if(mysqli_connect_error()){
			die('Failure connecting to the database! Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
		}
		//debug
		//echo 'Success... ' . mysqli_get_host_info($hDB) . "\n";
		return $hDB;
	}
	
	public static function getAllUsersAsObjects(){
		$sql = "SELECT * FROM user;";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!$res){
			die("Falhou ao obter todos utilizadores da aplicação");
		}
		if(mysqli_num_rows($res)){
			$objs=array();
			while($row = mysqli_fetch_assoc($res)){
				$objs[] = new User($row['userid']);
			}
			return $objs;
		}else{
			return array();
		}
	}
	
	public static function getUserData($userid){
		$sql = "SELECT * FROM user WHERE id='".$userid."';";
		$res = mysqli_query(DataManager::_getConnection(),$sql);
		if(!($res && mysqli_num_rows($res))){
			die("Falhou ao obter dados sobre a data do utilizador $userid!");
		}
		return mysqli_fetch_assoc($res);
	}
}
?>
Wrong SQL
Code:
create table user(
id int auto_increment,
email varchar(255) not null default '',
password varchar(255) not null default '',
primary key(id)
)engine=innodb;
Correct SQL
Code:
create table user(
userid int auto_increment,
semail varchar(255) not null default '',
spassword varchar(255) not null default '',
primary key(userid)
)engine=innodb;
 


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 Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Line object from two point objects and using objects as variables skf001 BOOK: Ivor Horton's Beginning Java, Java 7 Edition 4 May 15th, 2012 07:56 PM
Audit trail does not work for lists of EO objects luckystar BOOK: ASP.NET 3.5 Enterprise Application Development with Visual Studio 2008: Problem Design Solutio 2 June 12th, 2009 06:25 PM
Cant run Chapter03 romee BOOK: Beginning ASP.NET 2.0 BOOK VB ISBN: 978-0-7645-8850-1; C# ISBN: 978-0-470-04258-8 2 February 12th, 2007 05:31 PM
Chapter03 catriona BOOK: Beginning ASP.NET 2.0 BOOK VB ISBN: 978-0-7645-8850-1; C# ISBN: 978-0-470-04258-8 1 February 12th, 2007 07:42 AM
putting it another way MetsFan BOOK: Professional Crystal Reports for VS.NET 1 June 4th, 2004 12:12 PM



All times are GMT -4. The time now is 10:07 AM.


Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.