0

Hi there, happy new year to all!

I started using PDO few weeks ago, and I am trying to figure out what is the best way to use it....I just put 3 samples bellow and I was hoping you can tell me what is the most secure and professional way of using it.

<?
//db Connection
$db = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);

class account 
{ 
	function __construct()
	{
	global $db;	
	$this->db = $db;
	}
	
	
	function getRecord($account_id) 
	{ 
	$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
	$rs	 = $this->db->query($sql) or die("failed!");		
		while($row = $rs->fetch(PDO::FETCH_ASSOC)){
			$result[] = $row;
		}
	return $result;
	} 
}
$Account = new account();

// * 
// * OR
// *

class account 
{ 
	function __construct()
	{
	}
	
	function getRecord($account_id) 
	{ 
	global $db;	
	$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
	$rs	 = $this->db->query($sql) or die("failed!");		
		while($row = $rs->fetch(PDO::FETCH_ASSOC)){
			$result[] = $row;
		}
	return $result;
	} 

}
$Account = new account();

// * 
// * OR
// *

class account 
{ 
	function __construct($db)
	{
	$this->db = $db;		
	}
	
	function getRecord($account_id) 
	{ 
	$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
	$rs	 = $this->db->query($sql) or die("failed!");		
		while($row = $rs->fetch(PDO::FETCH_ASSOC)){
			$result[] = $row;
		}
	return $result;
	} 
}
$Account = new account($db);
?>
4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Stefano Mtangoo
0

The last one is IMHO the right way to do it. Since you are using classes, there should be no need for globals. Passing you DB class in the constructor for account is valid.

0

I use the last one too. Dunno if it's the best method though.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.