Jump to content

Is it worth making a database connection class?


svivian

Recommended Posts

At the moment I'm using a set of functions for connecting to a database, running queries and so on. I've heard a few people suggest using classes for this stuff, but examples I've seen are purely functions wrapped in a class, which is pointless - the class doesn't represent an object at all.

 

Are there any good ways to write these type of classes? I've got a few ideas:

- when running a query, store the "result resource" in a variable in the class; this helps keep db-specific code (eg mysql functions) out of the main script

- store row values internally: probably not worth doing since you generally want the data back every time you get results

 

The problem with storing things internally is that if you have nested query loops (eg looking up more data from the results you just got back) it fails because you overwrite the result resource from the outer loop, with the one in the inner loop.

 

Anyway... thoughts/suggestions welcome :)

Link to comment
Share on other sites

I would not be able to live without my database class, it makes creating certain queries a lot easier and you can automatically clean query values.  Now as for storing the query result in the database object, that is not smart and most popular database classes(like PEAR) do don't do that, you would do something like

 

$query = "SELECT a, b, c

FROM table_a

WHERE a = '1'";

$rows = $database->get_all($query);

 

foreach($rows as $row)

{

//another set of queries based on first query

}

Link to comment
Share on other sites

^But that's kinda my point. Wrapping the functions in a class has no use, aside from giving them a pseudo-namespace (which can be done with a function prefix, eg "dbQuery", "dbRow"). It would make sense if you're storing something within the class...

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.