Page 1 of 1

Why do this?

Posted: Fri Aug 18, 2006 4:07 pm
by s.dot

Code: Select all

<?php

/*
* MySQL Database Connection Class
* Date: 8-18-2006
* Author: scottayy@gmail.com
*/

class db
{
	var $host;
	var $user;
	var $pass;
	
	function connect($host,$user,$pass)
	{	
		$this->host = $host;
		$this->user = $user;
		$this->pass = $pass;
		
		return mysql_connect($this->host,$this->user,$this->pass);
	}
Is there any point in setting the class variables to that?

Posted: Fri Aug 18, 2006 4:15 pm
by feyd
With the code, as-is, the object's properties are useless as they'll be reset everytime connect() is called.

Posted: Fri Aug 18, 2006 4:20 pm
by s.dot
Well I'm wondering how I would pass that as a resource to the select_db function?

Code: Select all

function select_db($db_name)
{
   return mysql_select_db($db_name, <<resource link from connect()>>
}

Posted: Fri Aug 18, 2006 4:22 pm
by Oren
scottayy wrote:Well I'm wondering how I would pass that as a resource to the select_db function?

Code: Select all

function select_db($db_name)
{
   return mysql_select_db($db_name, <<resource link from connect()>>
}
You forgot a bracket.

Just kidding :P

Posted: Fri Aug 18, 2006 4:26 pm
by feyd
scottayy wrote:Well I'm wondering how I would pass that as a resource to the select_db function?
You don't pass it. It should be an internal only property of the DB object.

Posted: Fri Aug 18, 2006 4:27 pm
by s.dot
Suppose I could do it like this..

Code: Select all

function connect($host,$user,$pass,$db_name)
	{	
		mysql_select_db($db_name,$this->get_resource($host,$user,$pass));
	}
	
	function get_resource($host,$user,$pass)
	{
		return mysql_connect($host,$user,$pass);
	}
Seems kinda ugly though. I should probably look at an existing class to get a feel how it works before attempting to write my own. =/

Posted: Fri Aug 18, 2006 4:28 pm
by s.dot
feyd wrote:
scottayy wrote:Well I'm wondering how I would pass that as a resource to the select_db function?
You don't pass it. It should be an internal only property of the DB object.
Ah!

Posted: Fri Aug 18, 2006 4:32 pm
by s.dot
So something like this

Code: Select all

<?php

class db
{
	var $resource;
	
	function connect($host,$user,$pass)
	{	
		$this->resource = mysql_connect($host,$user,$pass);
	}
	
	function select_db($db_name)
	{
		mysql_select_db($db_name,$this->resource);
	}
	
}

?>
I could then connect by doing

Code: Select all

$db = new db();
$db->connect('localhost','user','pass');
$db->select_db('my_db');

Posted: Fri Aug 18, 2006 4:41 pm
by feyd
Image

Posted: Fri Aug 18, 2006 8:43 pm
by Christopher
Excellent. That is typically called a DB Connection class. Usually is also contains methods to execute a query, get post query values like last insert ID, begin and commit transactions, and get error number and message. The query method usually returns an object for select queries that can be a simple Record Set or an Active Record object which adds business logic and sometimes some O/RM.