473,378 Members | 1,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

PHP Database Class Instantiation

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
5 2306
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Drew McCormack | last post by:
I have a C++ template class which contains a static variable whose construction registers the class with a map. Something like this: template <typename T> class M { static Registrar<M>...
3
by: Patrick Guio | last post by:
Hi, I have trouble to compile the following piece of code with g++3.4 but not with earlier version // Foo.h template<typename T> class Foo { public:
23
by: mark.moore | last post by:
I know this has been asked before, but I just can't find the answer in the sea of hits... How do you forward declare a class that is *not* paramaterized, but is based on a template class? ...
8
by: akira2x3x | last post by:
Hello, I get this error while compiling with visualc++ and STL roguewave. With STL microsoft everything work fine. XXXData.cpp f:\xxxxx\product\rw\rcb1.2.0\rm\include\rw\_pair.h(63) : error...
1
by: Frederiek | last post by:
Hi, When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. Does that mean that the address of...
3
by: erictham115 | last post by:
Error C2555 c:\C++ projects\stat1\stdmatrix_adapt.h(41) : error C2555: 'std_tools::Matrix_adapter<T>::at': overriding virtual function return type differs and is not covariant from...
12
by: titan nyquist | last post by:
I have a class with data and methods that use it. Everything is contained perfectly THE PROBLEM: A separate thread has to call a method in the current instantiation of this class. There is...
8
by: Ole Nielsby | last post by:
I want to create (with new) and delete a forward declared class. (I'll call them Zorgs here - the real-life Zorks are platform-dependent objects (mutexes, timestamps etc.) used by a...
4
by: yuanhp_china | last post by:
I define a class in A.h: template <class Tclass A{ public: void get_elem( const T&) ; };
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.