By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,934 Members | 1,318 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,934 IT Pros & Developers. It's quick & easy.

PHP Database Class Instantiation

P: n/a
Here's a question that most will have different answers to. I'm just
dying to find a solution that seems halfway automated!! There really
are two seperate issues which might be answered by the same answer.

Web App:

- constants.php begin -
define("DB_HOST", "locahost");
.... to include the standard connection info
define("DB_NAME", "mydatabase");
- constants.php end -

- classes.php begin -

class Database {
function __construct() {
$link = mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME,$link);
}
function getData() {
$query = ...
$result = ...
while (...) {
$this->data['name'] = $row['name'];
...
}
}

}

class Stuff {
function __construct() {
$database = new Database <---- this does not seem to work
}
function getData() {
$database->getData();
$this->data = $database->data;
}

}

- classes.php end -
>From here, I can call the "data" field of the Stuff object with
$stuff->data.
I get: "Fatal error: Call to a member function getData() on a
non-object in ..." (it refers to the call in "Stuff | getData". So it
is obviously not seeing the Database object from within the Stuff
class.

So here are the questions (which many of you may have already spotted):
1) How can I get the Database class to recognize the constant db
credentials?
2) How can I get the Link class to call a method in the Database class
without having to automatically call "$database = new Database;" right
after the database class is written, then calling "global $database" in
the Link class. I HATE having to do that.

Any thoughts? I've seen many methods for doing this, like including
the db credentials IN the Database class construct method, but that
just seems out of place! I mean, sure, place the $link and db_select
stuff there, but not the credentials, right?

I'm hoping to stay as close to what I have up there as possible, like
just adding field scopes or something like that.

Any help is GREATLY appreciated.

Sep 2 '06 #1
Share this Question
Share on Google+
5 Replies


P: n/a
Here's a question that most will have different answers to. I'm just
dying to find a solution that seems halfway automated!! There really
are two seperate issues which might be answered by the same answer.

Web App:

- constants.php begin -
define("DB_HOST", "locahost");
... to include the standard connection info
define("DB_NAME", "mydatabase");
- constants.php end -

- classes.php begin -

class Database {
function __construct() {
$link = mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME,$link);
}
Why use globals here? If you define the database class with:

class Database
{private $link;
function __construct($host, $user, $password, $databasename)
{$this->link = mysql_connect($host, $user, $password);
mysql_select_db($databasename,$this->link);
}

etc. I personally would check the link after the connect.
function getData() {
$query = ...
$result = ...
while (...) {
$this->data['name'] = $row['name'];
...
}
}
I don't understand this one. What does it do? should it return
something? Is the query hardcoded in this function?
>
}

class Stuff {
function __construct() {
$database = new Database <---- this does not seem to work
}
Does it not work because of the syntax error? If so, switch on your
notices and warnings.
In my example, it should read:
$database = new Database(DB_HOST, DB_USER, DB_PASS, DB_NAME);

This way, you can pass other databases for testing or other users for
different roles (read / write / restructure).
function getData() {
$database->getData();
$this->data = $database->data;
}
This is by far easier to understand and maintain if you just have your
function use the return keyword. he getData method is really odd. It
does not accept input, and does not generate output either. Nonetheless,
I expect it to do some specialized job that generates output. Why isn't
it passed a query and returns the results?
>
}

- classes.php end -
>>From here, I can call the "data" field of the Stuff object with

$stuff->data.
I get: "Fatal error: Call to a member function getData() on a
non-object in ..." (it refers to the call in "Stuff | getData". So it
is obviously not seeing the Database object from within the Stuff
class.

So here are the questions (which many of you may have already spotted):
1) How can I get the Database class to recognize the constant db
credentials?
2) How can I get the Link class to call a method in the Database class
without having to automatically call "$database = new Database;" right
after the database class is written, then calling "global $database" in
the Link class. I HATE having to do that.

Any thoughts? I've seen many methods for doing this, like including
the db credentials IN the Database class construct method, but that
just seems out of place! I mean, sure, place the $link and db_select
stuff there, but not the credentials, right?

I'm hoping to stay as close to what I have up there as possible, like
just adding field scopes or something like that.

Any help is GREATLY appreciated.
Sep 2 '06 #2

P: n/a
Fantastic reply! Thanks for taking the time. I shall now attempt to
update my situation in order to hopefully clear up any confusion.

I figured out how to get the Stuff class to grab data from the Database
class. Here is an updated version of my code:
class Database {
function __construct() {
// Save the database credentials
$db['host'] = "localhost";
$db['user'] = "root";
$db['pass'] = "...";
$db['name'] = "tbl";
// Initialize the database connection
$link = mysql_connect($db['host'],$db['user'],$db['pass']);
mysql_select_db($db['name'],$link);
}
function getLinks() {
$query = "SELECT * FROM links";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$this->links[$row['id']]['label'] = $row['label'];
$this->links[$row['id']]['url'] = $row['url'];
$this->links[$row['id']]['location'] = $row['location'];
}
}
}

class Link {
function __construct() {
$this->database = new Database;
}
function getLinks() {
$this->database->getLinks();
$this->links = $this->database->links;
}
}
This is exactly what I'm using now, in fact. I've done away with the
arbitrary naming from before. So, the Link class instantiates a
Database object, then passes a request to it. The database object then
returns a variable which is then accessed by the index.php file and
displayed there in a foreach statement.

Your questions:

Why use a global? I'm not really even sure how to NOT use a global.
I'm assuming you're referring to the scope, right? This actually is
why I'm still on this thread. My question today ties directly into
this: How can I define some constants in a config.php file or something
of the like, then access those constants from within the Database class
directly without HAVING to pass the variables every time I instantiate
a Database object? As you can see now, I am actually declairing the
variables INSIDE of the database class... not my cup of tea.

What does the Stuff class do?
It's just a go between so the actually layout can access the database
through another layer. It makes sense in the grander scheme of my
application, just not here. I know it look unneccessary.

My question:

Was just asked in the "Why use a global?" answer.

Thanks as always for your help!!

Sep 5 '06 #3

P: n/a
Slant wrote:
Fantastic reply! Thanks for taking the time. I shall now attempt to
update my situation in order to hopefully clear up any confusion.

I figured out how to get the Stuff class to grab data from the Database
class. Here is an updated version of my code:
class Database {
function __construct() {
// Save the database credentials
$db['host'] = "localhost";
$db['user'] = "root";
$db['pass'] = "...";
$db['name'] = "tbl";
// Initialize the database connection
$link = mysql_connect($db['host'],$db['user'],$db['pass']);
mysql_select_db($db['name'],$link);
}
function getLinks() {
$query = "SELECT * FROM links";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$this->links[$row['id']]['label'] = $row['label'];
$this->links[$row['id']]['url'] = $row['url'];
$this->links[$row['id']]['location'] = $row['location'];
}
}
}

class Link {
function __construct() {
$this->database = new Database;
}
function getLinks() {
$this->database->getLinks();
$this->links = $this->database->links;
}
}
This is exactly what I'm using now, in fact. I've done away with the
arbitrary naming from before. So, the Link class instantiates a
Database object, then passes a request to it. The database object then
returns a variable which is then accessed by the index.php file and
displayed there in a foreach statement.

Your questions:

Why use a global? I'm not really even sure how to NOT use a global.
I'm assuming you're referring to the scope, right? This actually is
why I'm still on this thread. My question today ties directly into
this: How can I define some constants in a config.php file or something
of the like, then access those constants from within the Database class
directly without HAVING to pass the variables every time I instantiate
a Database object? As you can see now, I am actually declairing the
variables INSIDE of the database class... not my cup of tea.

What does the Stuff class do?
It's just a go between so the actually layout can access the database
through another layer. It makes sense in the grander scheme of my
application, just not here. I know it look unneccessary.

My question:

Was just asked in the "Why use a global?" answer.

Thanks as always for your help!!
PMJI,

Generally I pass the values to the database class. The main reason is
for security; a second is versatility.

For instance - I might have one user for almost everyone who can read
the database but not update it (or at least certain tables) - or at
least only insert/update. But an admin user would be able to perform
additional operations.

That way the "public" user would have limited privileges, while admin
would have full privileges. It helps in case for some reason the
password gets out (i.e. screwed up Apache configuration) and/or someone
tries a SQL injection attack that I didn't catch.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Sep 5 '06 #4

P: n/a
Alright those are some darned good reasons. Thanks for taking the time
to explain those. So how to you pass the variables? Just through the
class instantiation from within the other class? Or do you do it from
variables you actually DECLAIR in the calling class? I'm assuming the
former from your statement. Thus might bring me to another question.
Do you have multiple sets of user access credentials, one for each user
of which you spoke earlier? Thus you could access these credentials
anytime you'd like. Or how does that work?

Thanks again!
Jerry Stuckle wrote:
Slant wrote:
Fantastic reply! Thanks for taking the time. I shall now attempt to
update my situation in order to hopefully clear up any confusion.

I figured out how to get the Stuff class to grab data from the Database
class. Here is an updated version of my code:
class Database {
function __construct() {
// Save the database credentials
$db['host'] = "localhost";
$db['user'] = "root";
$db['pass'] = "...";
$db['name'] = "tbl";
// Initialize the database connection
$link = mysql_connect($db['host'],$db['user'],$db['pass']);
mysql_select_db($db['name'],$link);
}
function getLinks() {
$query = "SELECT * FROM links";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$this->links[$row['id']]['label'] = $row['label'];
$this->links[$row['id']]['url'] = $row['url'];
$this->links[$row['id']]['location'] = $row['location'];
}
}
}

class Link {
function __construct() {
$this->database = new Database;
}
function getLinks() {
$this->database->getLinks();
$this->links = $this->database->links;
}
}
This is exactly what I'm using now, in fact. I've done away with the
arbitrary naming from before. So, the Link class instantiates a
Database object, then passes a request to it. The database object then
returns a variable which is then accessed by the index.php file and
displayed there in a foreach statement.

Your questions:

Why use a global? I'm not really even sure how to NOT use a global.
I'm assuming you're referring to the scope, right? This actually is
why I'm still on this thread. My question today ties directly into
this: How can I define some constants in a config.php file or something
of the like, then access those constants from within the Database class
directly without HAVING to pass the variables every time I instantiate
a Database object? As you can see now, I am actually declairing the
variables INSIDE of the database class... not my cup of tea.

What does the Stuff class do?
It's just a go between so the actually layout can access the database
through another layer. It makes sense in the grander scheme of my
application, just not here. I know it look unneccessary.

My question:

Was just asked in the "Why use a global?" answer.

Thanks as always for your help!!

PMJI,

Generally I pass the values to the database class. The main reason is
for security; a second is versatility.

For instance - I might have one user for almost everyone who can read
the database but not update it (or at least certain tables) - or at
least only insert/update. But an admin user would be able to perform
additional operations.

That way the "public" user would have limited privileges, while admin
would have full privileges. It helps in case for some reason the
password gets out (i.e. screwed up Apache configuration) and/or someone
tries a SQL injection attack that I didn't catch.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Sep 6 '06 #5

P: n/a
Slant wrote:
Jerry Stuckle wrote:
>>Slant wrote:
>>>Fantastic reply! Thanks for taking the time. I shall now attempt to
update my situation in order to hopefully clear up any confusion.

I figured out how to get the Stuff class to grab data from the Database
class. Here is an updated version of my code:
class Database {
function __construct() {
// Save the database credentials
$db['host'] = "localhost";
$db['user'] = "root";
$db['pass'] = "...";
$db['name'] = "tbl";
// Initialize the database connection
$link = mysql_connect($db['host'],$db['user'],$db['pass']);
mysql_select_db($db['name'],$link);
}
function getLinks() {
$query = "SELECT * FROM links";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$this->links[$row['id']]['label'] = $row['label'];
$this->links[$row['id']]['url'] = $row['url'];
$this->links[$row['id']]['location'] = $row['location'];
}
}
}

class Link {
function __construct() {
$this->database = new Database;
}
function getLinks() {
$this->database->getLinks();
$this->links = $this->database->links;
}
}
This is exactly what I'm using now, in fact. I've done away with the
arbitrary naming from before. So, the Link class instantiates a
Database object, then passes a request to it. The database object then
returns a variable which is then accessed by the index.php file and
displayed there in a foreach statement.

Your questions:

Why use a global? I'm not really even sure how to NOT use a global.
I'm assuming you're referring to the scope, right? This actually is
why I'm still on this thread. My question today ties directly into
this: How can I define some constants in a config.php file or something
of the like, then access those constants from within the Database class
directly without HAVING to pass the variables every time I instantiate
a Database object? As you can see now, I am actually declairing the
variables INSIDE of the database class... not my cup of tea.

What does the Stuff class do?
It's just a go between so the actually layout can access the database
through another layer. It makes sense in the grander scheme of my
application, just not here. I know it look unneccessary.

My question:

Was just asked in the "Why use a global?" answer.

Thanks as always for your help!!

PMJI,

Generally I pass the values to the database class. The main reason is
for security; a second is versatility.

For instance - I might have one user for almost everyone who can read
the database but not update it (or at least certain tables) - or at
least only insert/update. But an admin user would be able to perform
additional operations.

That way the "public" user would have limited privileges, while admin
would have full privileges. It helps in case for some reason the
password gets out (i.e. screwed up Apache configuration) and/or someone
tries a SQL injection attack that I didn't catch.

Alright those are some darned good reasons. Thanks for taking the time
to explain those. So how to you pass the variables? Just through the
class instantiation from within the other class? Or do you do it from
variables you actually DECLAIR in the calling class? I'm assuming the
former from your statement. Thus might bring me to another question.
Do you have multiple sets of user access credentials, one for each user
of which you spoke earlier? Thus you could access these credentials
anytime you'd like. Or how does that work?

Thanks again!

(Top posting fixed)

Typically I'll pass them in the constructor for the object or the open()
method. If they're passed in the constructor, I open the connection
immediately. Otherwise I open it in the open() method.

Then the database class object would be passed as a parameter to the
links object. It allows for the same database object to be used by
several other objects. I wouldn't create it in the links class.

Also, your getLinks() method should be part of the Link class. The
database class should have things related to the entire database itself,
not a specific table. It makes it more reusable.

Typically my database class will only have methods such as the
constructor, open, close, etc. If you want to make it database
independent, you could even add things like query(), etc. to it, and
call mysql_query() from there. But if you don't care about that part,
just call mysql_query() from your Link class.

So you might be something like:

$db = new Database($host, $user, $pass);
$link = new Link($db);
$links = link->getLinks();

And yes, I have different users with different privileges, depending on
the need at the time.

P.S. Please don't top post. Thanks.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Sep 6 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.