Jump to content

Looking for a little help creating a DB class.


kellendil

Recommended Posts

I'm trying to make a very simple DB class, but haven't quite gotten the hang for using classes, to put it mildly.

Anyway, I'm making this class, with just a few functions, mainly to make, and use a class. Expanding on it later when I have a working one, should not be a big problem.

The class is, as mentioned, a database class, I want it to have the following 3 functions:
-Open a connection, with variables listed within the class
-Execute a query
-Close connection.

My own feeble attempt:
[code]
class database {

var $dbhost = 'serveradress';
var $dbusername = 'username';
var $dbpasswd = 'password'; 
var $database_name = 'dbname';

//open connection.
function sqlOpen($dbhost,$dbusername,$dbpasswd) {
$connection = mysql_connect("$dbhost","$dbusername","$dbpasswd")
or die ("Couldn't connect to server.");

$db = mysql_select_db("$database_name", $connection)
or die("Couldn't select database.");

return $db;
}

//close connection.
function sqlClose($connection) {
mysql_close($connection);
}
}[/code]

As you can see, I haven't included any code for executing a query, but I don't think that will pose a huge problem.

Anyway, if someone could help me out or point me in the correct direction, and perhaps give me an example of how a class like this would be used (spesifically the opening of a database connection) I would be very very grateful :)

-Kellendil
Link to comment
Share on other sites

So let me get this straight. Youve made a class but don't know how to use it? Firstly... you really dont need the sqlOpen function to return anything, just have it set a private connection variable that can then be used within the class.

Really, the class itself should take care of instigating connections too, you shouldn't need to specifically call a method to open a connection.

Basically, all the code in your example isn't really needed (or wanted) within a database class.
Link to comment
Share on other sites

As I said, it was a feeble attempt, I know that it isn't correct, which is why I'm asking for help :]

[quote]Really, the class itself should take care of instigating connections too, you shouldn't need to specifically call a method to open a connection.[/quote]

This is what I've read elsewhere as well, but I haven't been able to find a good example, so I don't really understand how I do it.
[quote]Basically, all the code in your example isn't really needed (or wanted) within a database class.[/quote]

How does one close a database connection then (manually, I know that it isn't usually necessary)

-Kellendil
Link to comment
Share on other sites

You should code your class on a different approach:

What should this class do ?
- Create a connection
- Execute queries with the made connection
- Close your connection if asked.
What shouldn't this class do?
- Error handling !!!
- Configuration !!!

[code]
<?php
require_once('dbConfiguration.inc.php');

class database {
  private $config = $GLOBALS['dbConfig'];
  private $db = null;
  public $errorMessage = null;
 
  function database($dbName) {
    $this->db = mysql_connect($this->config['dbHost'], $this->config['dbUser'], $this->config['dbPassword'])
    or $this->errorMessage = mysql_error();
    if($this->db) {
      mysql_select_db($dbName, $this->db) or $this->errorMessage = mysql_error();
    }
  }

  function sqlClose() {
  mysql_close($this->db)or $this->errorMessage = mysql_error();
  }

  function sqlQuery($query) {
    $results = null;
    $results = mysql_query($query, $this->db) or $this->errorMessage = mysql_error();
    return $results;
  }

  function getErrorMessage() {
    return $errorMessage;
  }
}
?>


How to use this class:
<?php
require_once('database.class.php');

$db = new database('DatabaseName');  // Makes connection
// Your script that uses the class chooses whatever to do with the generated errors !!!
if($error = $db->getErrorMessage()) {
  exit($error);
}

$query = "SELECT * FROM table";
if(!$results = $db->sqlQuery($query)) {
// Again: Your script that uses the class chooses whatever to do with the generated errors !!!
exit($db->getErrorMessage());
}

if(!$db->sqlClose()) {
  // And again: Your script that uses the class chooses whatever to do with the generated errors !!!
exit($db->getErrorMessage());
}

/*
This script does not wanna know how the connection is made, does not wanna know the db connection link !!!
This script handles the database errors output !!!
....
*/

?>
[/code]
Link to comment
Share on other sites

Thanks alot, lets see if I understand it all :>

[code]require_once('dbConfiguration.inc.php');[/code] ok, this is where i put my configuration, in your example it would look something like this?
[code]
<?php
//configuration file for databaseconnection.
$dbconfig['dbHost'] = 'databasehost';
$dbconfig['dbUser'] = 'databaseusername';
$dbconfig['dbPassword'] = 'databasepass'; 
?>
[/code]

The rest of the code is pretty self explanatory, so I won't ask stupid questions about that :]

You are absolutely correct about seperating the errorhandling and configuration, I should have though about that myself, but as I mentioned, I'm fairly new to the OO approach :)

Thanks again for your help :)

-Kellendil
Link to comment
Share on other sites

The idee to seperate your error handling from all other classes is to create a class specially for this.
Now you could make a class errors or something like that that will keep all your generated errors into
a database (by using your database class) or error log file. And on every page of your application/site
you could aks the errorClass the latest error to display if any new errors where added.

something like:
[code]
<?php
require_once('error.class.php');
require_once('database.class.php');

$cError = new Error();
$cDatabase = new Database();

$cDatabase = new Database('databaseName');
if($error = $cDatabase->getErrorMessage()) {
$cError->add(ERROR_CRITICAL, $error);
}
?>
[/code]

And you could add in your pages header or footer:
[code]
<?php
if($cError->newError()) {
  $echo "<font color='red'>" . $cError->lastError() . "</font>";
}
?>
[/code]

And indeed in your dbConfiguration.inc.php you put all your configurations.

You should know that programming OO is to extract all specific functionalities into an object/class and only these specific functionalities. So if you create a database class you should only create the functionalities that concern databases into this class. And so on ...
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.