473,757 Members | 7,200 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(D B_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 2333
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(D B_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($ho st, $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_HOS T, 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($qu ery) or die(mysql_error ());
while($row = mysql_fetch_arr ay($result,MYSQ L_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($qu ery) or die(mysql_error ());
while($row = mysql_fetch_arr ay($result,MYSQ L_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*******@attgl obal.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($qu ery) or die(mysql_error ());
while($row = mysql_fetch_arr ay($result,MYSQ L_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*******@attgl obal.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($qu ery) or die(mysql_error ());
while($row = mysql_fetch_arr ay($result,MYSQ L_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
applicatio n, 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*******@attgl obal.net
=============== ===
Sep 6 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2479
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> registrar; }; The constructor of Registrar does the registering when it is initialized.
3
8257
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
3858
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? Here's what I thought should work, but apparently doesn't: class Foo; void f1(Foo* p)
8
2544
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 C2079: 'first' uses undefined class 'Node' f:\xxxxx\product\rw\rcb1.2.0\rm\include\vector(404) : see reference to class template instantiation 'std::pair<class Node,bool>'
1
2298
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 the data member is the same for every instance of that class? I would expect so, but I noticed something that makes me doubt a little.
3
2961
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 'ple::imtx_impl<T>::at' //in my program: the derived class template <class T> class Matrix_adapter : public ple::imtx_impl<T{ protected:
12
3119
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 only ever ONE instantiation of this class, and this outside method in a separate thread has to access it. How do i do this?
8
2144
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 cross-platform scripting engine. When the scripting engine is embedded in an application, a platform-specific support library is linked in.) My first attempt goes here: ---code begin (library)---
4
2489
by: yuanhp_china | last post by:
I define a class in A.h: template <class Tclass A{ public: void get_elem( const T&) ; };
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.