As the title says:
I've written a class in php to give me a simple db-interface
(yes, yes, I know there are hundreds of them already, but I need to learn as well)
and it works fine with the exception of one thing.
I'd like it to create the initial connection as I instansiate the class.
I've made a constructor that is supposed to call a method/function inside the class to create the connection
but I still need to call that function separately to set the connection within the class.
What have I done wrong?
Here's the code for the class:
code:
////////////////////// Class for DB-Access /////////////////////////
class cDbInterface {
var $connection;
/*config connection to database*/
var $host = 'localhost';
var $user = '';
var $password = '';
var $db = 'filearchive';
//Variables that will hold
var $result;
var $items = array();
//Constructor, sets a valid connection
function cDbInterface(){
$this-> connection = hookUpDb;
}
//Generates the connection with the database and returns a
//valid connection for the one calling.
function hookUpDb(){
/*connect to the database*/
if(mysql_connect($this->host,$this->user,$this->password)){
$this->connection = mysql_connect($this->host,$this->user,$this->password);
mysql_select_db($this->db,$this->connection);
return $this->connection;
}else{
return mysql_error();
}
}
/////////////////////////////////////////////////////
////////////////////// Generic QueryAskers///////////
//Use when no returned result is excepted.
//returns true or mysql_error.
function doQuery($sql){
if(!mysql_query($sql,$this->connection)){
return mysql_error();
}
return true;
}
//Use this when you need to use custom made SQL-queries on the database.
//Returns a 2 dimensional array with the result.
function doQueryResult($sql){
if($sql != ""){
$this->result = mysql_query($sql,$this->connection);
$item = array();
while($item = mysql_fetch_array($this->result)){
$this->items[] = $item;
}
return $this->items;
mysql_free_result($this->result);
}else{
return mysql_error();
}
}
//Closes connection to the database.
function closeCon(){
mysql_close($this->connection);
return true;
}
}
/////////////////////////////////////////////
And I have to use it like this:
code:
$dbCon = new cDbInterface;
$dbCon->hookUpDb(); //<------ this is the line that I shouldn't need to use...
$results = $dbCon->doQueryResult('SELECT * FROM filetypes');
foreach($results as $result){
print("<p> Arkiv id ".$result['archive_id']." tillåter ".$result['filetype']."-filer");
}
$dbCon->closeCon();
Any tips?
/Dan
{cell 260}
-{ a vibration is a movement that doesn't know which way to go }-