Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

database query's from class object with php

My question is:

Can I still do query's from within an object like this:

$result = mysql_query ($q,$dbc) 
          or 
          trigger_error("Query: $q\n<br />MySQL Fout: " . mysql_error($dbc));

by passing the global dbconnection variable $dbc to the constructor

or is there a better way?

Or creating a singleton class for the databaseconnection, but I see a lot off negativity that people are writing about it.

I am new to making objects, so I don't know if I mayby have to do it all a little different, with the db I mean.

thanks, Richard

like image 257
Richard Avatar asked Jul 05 '26 07:07

Richard


1 Answers

If you looking for database abstraction, why not consider using the DB classes provided by Zend Framework.

They also include a way to set an adapter as the default, making it a snap to perform operations.

Add to that the fact that Zend_Db defaults to using parameterised queries instead of old fashioned quoted ones, thus adding security and peace of mind.

using globals is pretty much a bad idea, its far too easy to accidentally overwrite one! along with all the other reasons you will find for not using them with a quick google.

Making a db connection with Zend Framework is a snap,

$db = Zend_Db::factory('Pdo_Mysql', array(
'host'     => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname'   => 'test'

));

It really is as simple as that. you can then either make your table classes to provide quick access to individual tables, or use the select and statement objects for more advanced joined querys.

Also, with Zend Framework, you do not have to use the whole stack, you can simply use just the DB components if you like.

If you don't want to use Zend Framework for this, I would strongly recommend you consider alternatives such as an ORM like Doctrine over writing your own DB abstraction. you will end up with a monster very quickly, and an ORM or Zend Framework have a great many developers squashing bugs, and even more reporting any that are there.

like image 88
Bittarman Avatar answered Jul 06 '26 21:07

Bittarman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!