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);
?>

Recommended Answers

All 3 Replies

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.

Member Avatar for diafol

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

Last one is the best plus, use parametric queries (Bind/execute)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.