473,387 Members | 1,575 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,387 software developers and data experts.

OOP PHP with MySQLi

Hey, i'm looking for the best possible way for connecting to my database
without too much of an effort.

The example works fine and fast. What i need to know is if it's safe, stable
and the way to go. If anyone has a better way for connecting side-wide to
something i'd like you to show me. I've had it working before using 'global'
but people told me 'global' is bad programming.

One of the possibilities would be to make the link and pass it on to every
function and object but this is NOT an option because it makes my script
less transparant and easy to read.
<?php

class My {
private static $connection;

function SQL() {
if(empty(self::$connection)) {
self::$connection = new mysqli("localhost", "user", "password", "db");
}
return self::$connection;
}
}

class User {
function __construct() {
echo "user init<p>";
}

public function show() {
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
}
}

$user = new User();
$user->show();

//Works here too
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
?>
Jan 31 '06 #1
7 2154
Citrus wrote:
Hey, i'm looking for the best possible way for connecting to my database
without too much of an effort.

The example works fine and fast. What i need to know is if it's safe,
stable and the way to go. If anyone has a better way for connecting
side-wide to something i'd like you to show me. I've had it working before
using 'global' but people told me 'global' is bad programming.

One of the possibilities would be to make the link and pass it on to every
function and object but this is NOT an option because it makes my script
less transparant and easy to read.
<?php

class My {
private static $connection;

function SQL() {
if(empty(self::$connection)) {
self::$connection = new mysqli("localhost", "user", "password",
"db");
}
return self::$connection;
}
}

class User {
function __construct() {
echo "user init<p>";
}

public function show() {
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
}
}

$user = new User();
$user->show();

//Works here too
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
?>

What a lot of overhead and such.
I am glad I just use global $connection; whereever I need it.

begining of every script that need a db:
<? require_once('dnconnect.php'); ?>

then from a function:
function leaveThingsSimple(){
global $connection;
// do stuff here
}

Bad programming?
Says who?
And why?

Only use Objects if they add something to your code or structure somehow.
(Like PEAR:DB)
I really don't see the problem with making $connection global...

Regards,
Erwin Moller
Jan 31 '06 #2
> What a lot of overhead and such.
I am glad I just use global $connection; whereever I need it.


Where exactly do you find any overhead ? My project will consist out of 15
or more objects with each over 20 or 30 functions. Almost every function
will need to use a database connection. Calling global $connection at the
start of every script and function.. THAT is overhead.

I'm happy with my solution and it's a joy to work with. Currently i'm
working on the foundations wich I feel is very important (i've done 2 major
projects before) and with the upcoming PHP6 i want everything to be done by
the (right) book.
In the meanwhile i've had confirmation that this IS a good way and there
should only be a 'public' statement before function SQL.
So if any people are interested:

<?php

class My {
private static $connection;

public function SQL() {
if(empty(self::$connection)) {
self::$connection = new mysqli("localhost", "login", "password",
"database");
if(mysqli_connect_errno()) {
trigger_error("Could not connect to database !
".mysqli_connect_error()."", E_USER_ERROR);
}
}
return self::$connection;
}
}

?>

If you load the upper code in every script you can easily comunicate with
your database using
My::SQL()->query();

Best thing is that you can use this in every function or object without
having the need to call anything else.
Jan 31 '06 #3
Citrus wrote:
What a lot of overhead and such.
I am glad I just use global $connection; whereever I need it.


Where exactly do you find any overhead ? My project will consist out of 15
or more objects with each over 20 or 30 functions. Almost every function
will need to use a database connection. Calling global $connection at the
start of every script and function.. THAT is overhead.


No it is not.
That is just an opinion.
How do you want to compare? Counting?

But all is fine with me: Code whatever way feels good and structured to you.

I just do not see the advantage, but that is not important.

Don't get me wrong: I come from a Java (J2EE) background so I know my way
just fine with objects.
That is also why I like PHP so much: I can throw in objects when I need
them, where Java made me use objects for even the most simplest
functionality.
I often see people getting all happy and joyous about objects, while object
are just another way of doing what you were doing before without objects.
Smart designed functions can give you almost the same flexibility.
I just had the impression you wanted to use objects for your connection,
because that sounded cool, and I just wanted to tell you there is nothing
wrong with global $connection.

But I still wonder why you said that global $connection is bad programming.
Care to explain that?
I am just curious what made you claim that.

Regards,
Erwin Moller
Jan 31 '06 #4
Erwin Moller wrote:
Citrus wrote:

Hey, i'm looking for the best possible way for connecting to my database
without too much of an effort.

The example works fine and fast. What i need to know is if it's safe,
stable and the way to go. If anyone has a better way for connecting
side-wide to something i'd like you to show me. I've had it working before
using 'global' but people told me 'global' is bad programming.

One of the possibilities would be to make the link and pass it on to every
function and object but this is NOT an option because it makes my script
less transparant and easy to read.
<?php

class My {
private static $connection;

function SQL() {
if(empty(self::$connection)) {
self::$connection = new mysqli("localhost", "user", "password",
"db");
}
return self::$connection;
}
}

class User {
function __construct() {
echo "user init<p>";
}

public function show() {
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
}
}

$user = new User();
$user->show();

//Works here too
$query = My::SQL()->query("SELECT * FROM user");
while($row = $query->fetch_object()) {
echo $row->login."<p>";
}
?>


What a lot of overhead and such.
I am glad I just use global $connection; whereever I need it.

begining of every script that need a db:
<? require_once('dnconnect.php'); ?>

then from a function:
function leaveThingsSimple(){
global $connection;
// do stuff here
}

Bad programming?
Says who?
And why?

Only use Objects if they add something to your code or structure somehow.
(Like PEAR:DB)
I really don't see the problem with making $connection global...

Regards,
Erwin Moller

Yes, bad programming. It binds all of your code to the variable
$connection, among other things. If you need to change that you have a
huge amount of code to change. It also makes the code less portable.
Also, if $connection gets changed someplace, you'll have a hell of a
time trying to debug it.

Globals in general are bad ideas.

Citrus's design is much better. There is a little overhead - but not
all that much.

And I find objects almost always improve the structure of my code. It
also makes it more flexible and configurable. For instance - I can
easily change databases simply by changing the database object. No
changes in my code are necessary. Heck - I can even use flat files when
necessary!

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Jan 31 '06 #5
Jerry Stuckle wrote:
Erwin Moller wrote:
<snip>

Bad programming?
Says who?
And why?

Only use Objects if they add something to your code or structure somehow.
(Like PEAR:DB)
I really don't see the problem with making $connection global...

Regards,
Erwin Moller

Yes, bad programming. It binds all of your code to the variable
$connection, among other things.


No, I use it only in functions that need the connection.
If a script needs the connection it gets the connection by means of a
include at top of the script.
If you need to change that you have a huge amount of code to change.
Why should somebody want to change the connection-object?
It is needed for database-access.
If I need to change that I am really making a new program.
It also makes the code less portable. Also, if $connection gets changed someplace, you'll have a hell of a
time trying to debug it.
Sorry, thanks for replying, and I do not want to pick a fight with you, but
this doesn't make sense.
I can say the same for your object-oriented approach, look:

- If you use an (singleton) Object to deliver the connection, you bind all
your code to that object.
and
- If the connection in the object somehow get changed, all code breaks.
and

Does that make sense to you?
Of course not!
You know where you need a databaseconnection and get it delivered somehow,
singleton Object or global connection.
Both are lines of code, and both deliver the same in the end: a working
connection.

Globals in general are bad ideas.
Not if you need an outside variable inside a function.
It is perfectly legal.

I could also deliver the connection by refrence every call to every function
that needs the connection.

No big diff.

Please remember that we are NOT talking about globals as in ASP
(Application), but just globals for the duration of the script.

Citrus's design is much better. There is a little overhead - but not
all that much.
Yes, Citrus claimed the same.
Also without any argumentation that made any sense.

If you are so sure of the superiority of the Object approach, why can you
not tell us why?


And I find objects almost always improve the structure of my code. It
also makes it more flexible and configurable. For instance - I can
easily change databases simply by changing the database object. No
changes in my code are necessary.
No changes in your code needed?
Of course you need to change something in your code, the Object that makes
the connection is changed by you.

Now compare this to an include that delivers the connection: I also have 1
place to change the connection, and it is included everywhere.
Then everywhere where 'global $connection;' is used, the connection is
up-to-date.

Don't try to sell nonsense to me.
I developed years and years in Java, and do not fall for laymans arguments.

Please give me a serious response that dives into the issue instead of
claims that are clearly not true.
Another thing: In PHP Objects are only halfhearted and last only for the
duration of the script. They are not persistent. (Unless of course you
serialize and deserialize them from script to script, but that is not
exactly persistent.)
Object in PHP are nothing more than a bundling of some functions together,
and their own namespace. Really that is all there is to it.

Don't try to make more of it than that.
Heck - I can even use flat files when necessary!


So can I, but what has that to do with this issue?
Are you suggesting that Objects are the next step in evolution of the
$connection in scripts? Haha.
Regards,
Erwin Moller

Feb 1 '06 #6
Erwin Moller wrote:
Jerry Stuckle wrote:


Yes, bad programming. It binds all of your code to the variable
$connection, among other things.

No, I use it only in functions that need the connection.
If a script needs the connection it gets the connection by means of a
include at top of the script.


Yes, and declaring something global has its own overhead.

If you need to change that you have a
huge amount of code to change.

Why should somebody want to change the connection-object?
It is needed for database-access.
If I need to change that I am really making a new program.


Well, lets say you change hosting companies - and the new one uses
PostGres. Or you want to use the code on something which requires
Oracle access. Or any number of things.

It also makes the code less portable.
Also, if $connection gets changed someplace, you'll have a hell of a
time trying to debug it.

Sorry, thanks for replying, and I do not want to pick a fight with you, but
this doesn't make sense.
I can say the same for your object-oriented approach, look:

- If you use an (singleton) Object to deliver the connection, you bind all
your code to that object.
and
- If the connection in the object somehow get changed, all code breaks.
and


First of all, it was not MY singleton object. But it's a heck of a lot
more portable than yours is.

Yes, you bind your code to that object. But that object itself can
change. Right now it uses MySQL. Later it can use Postgres, Oracle or
even flat files. No change to the code using it.
Does that make sense to you?
Of course not!
Of course it does!
You know where you need a databaseconnection and get it delivered somehow,
singleton Object or global connection.
Both are lines of code, and both deliver the same in the end: a working
connection.

But an object is a lot more than a line of code.
Globals in general are bad ideas.

Not if you need an outside variable inside a function.
It is perfectly legal.


And this one statement tells me that you've never worked in a commercial
programming environment. What's "legal" is not necessarily "good
programming practice".
I could also deliver the connection by refrence every call to every function
that needs the connection.

No big diff.

Huge difference. But you obviously have made your mind up. Just please
- don't promote your poor programming practices on naive new programmers!
Please remember that we are NOT talking about globals as in ASP
(Application), but just globals for the duration of the script.

Yes, I know EXACTLY what we're talking about!


Citrus's design is much better. There is a little overhead - but not
all that much.

Yes, Citrus claimed the same.
Also without any argumentation that made any sense.

If you are so sure of the superiority of the Object approach, why can you
not tell us why?


I tried. You obviously aren't listening!
And I find objects almost always improve the structure of my code. It
also makes it more flexible and configurable. For instance - I can
easily change databases simply by changing the database object. No
changes in my code are necessary.

No changes in your code needed?
Of course you need to change something in your code, the Object that makes
the connection is changed by you.


No, the OBJECT code changes. MY CODE does not!
Now compare this to an include that delivers the connection: I also have 1
place to change the connection, and it is included everywhere.
Then everywhere where 'global $connection;' is used, the connection is
up-to-date.

Don't try to sell nonsense to me.
I developed years and years in Java, and do not fall for laymans arguments.

I've been programming since 1967 (in Fortran I). I've written C++ for 18
years, some of them as a programmer for IBM. I've been writing Java for
over 10 years. And since then I've been a successful consultant,
writing code and managing projects.

Hardly a layman.
Please give me a serious response that dives into the issue instead of
claims that are clearly not true.

I have, but you obviously have made up your mind.

Another thing: In PHP Objects are only halfhearted and last only for the
duration of the script. They are not persistent. (Unless of course you
serialize and deserialize them from script to script, but that is not
exactly persistent.)
So? The same is true for any program!
Object in PHP are nothing more than a bundling of some functions together,
and their own namespace. Really that is all there is to it.

And you obviously don't want to understand.
Don't try to make more of it than that.
Heck - I can even use flat files when
necessary!
So can I, but what has that to do with this issue?
Are you suggesting that Objects are the next step in evolution of the
$connection in scripts? Haha.


The fact is - I can do it without any changes to my code!

Regards,
Erwin Moller


But this conversation is at an end. I don't argue with close-minded idiots.

Here's a tag line for you:

"My mind is made up. Don't confuse me with the facts!"

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Feb 1 '06 #7
Jerry Stuckle wrote:
Erwin Moller wrote:
Jerry Stuckle wrote:


Yes, bad programming. It binds all of your code to the variable
$connection, among other things.

No, I use it only in functions that need the connection.
If a script needs the connection it gets the connection by means of a
include at top of the script.


Yes, and declaring something global has its own overhead.


Like putting the reference into the global-array?
Wow, THAT is overhead.

Let's double the memory in the server right away!

If you need to change that you have a
huge amount of code to change.

Why should somebody want to change the connection-object?
It is needed for database-access.
If I need to change that I am really making a new program.


Well, lets say you change hosting companies - and the new one uses
PostGres. Or you want to use the code on something which requires
Oracle access. Or any number of things.


In that case I change my connectstring IN ONE PLACE.

Just as you do in your connection-object.

Your point being?


It also makes the code less portable.
Also, if $connection gets changed someplace, you'll have a hell of a
time trying to debug it.

Sorry, thanks for replying, and I do not want to pick a fight with you,
but this doesn't make sense.
I can say the same for your object-oriented approach, look:

- If you use an (singleton) Object to deliver the connection, you bind
all your code to that object.
and
- If the connection in the object somehow get changed, all code breaks.
and


First of all, it was not MY singleton object. But it's a heck of a lot
more portable than yours is.


That is what you keep claiming.
Now give some argumentation please, because I know what your opinion is, and
honestly, it is NOT getting any more convincing by repeating it.


Yes, you bind your code to that object. But that object itself can
change. Right now it uses MySQL. Later it can use Postgres, Oracle or
even flat files. No change to the code using it.
That depends solely on the fact if you use a databaseabstractionlayer or
not.
You cannot just 'change database' without one, and you know that.
A lot of SQL-functionality is implemented differently on different
databases.

You need some ODBC or ADODB or another approach to reach that flexibility,
and it has zero to do with how some connection-object is found in a script.

If you do not agree, tell me why.

You know where you need a databaseconnection and get it delivered
somehow, singleton Object or global connection.
Both are lines of code, and both deliver the same in the end: a working
connection.

But an object is a lot more than a line of code.


Really?

My eyes are opening....

Globals in general are bad ideas.

Not if you need an outside variable inside a function.
It is perfectly legal.


And this one statement tells me that you've never worked in a commercial
programming environment. What's "legal" is not necessarily "good
programming practice".


I think you don't see the difference between a global in PHP and a global in
other many other languages.

Globals in PHP last for the duration of the script whereas the more usual
global means something is available to all processes running.
for example: In J2EE you can store stuff in ServletContext, In IIS/ASP in
Application, and that is where they stay, can get corrupted, etc.
But that is not how things work in PHP.

Go study the subject a bit more, then come back and try to insult me.
Ok?

About the commercial programming environment: Don't worry. Been there.
Did that. They pay me well. :P
I run my own softwarecompany now for years.
Mainly so I do not have to cooperate with zealots with low coding-experience
that resonate with each and every hype they hear about.

OOP?
Learned it, liked it, use it when appropriate.

Once again: I have 0 problems with somebody using a singleton database
connection design. 0 problems.

I DO have problems with your arrogant attitude.

If you were speaking with any authority, I might learn a thing or two, but
so you only repeated your invalid arguments.
Back them up.
I could also deliver the connection by refrence every call to every
function that needs the connection.

No big diff.

Huge difference. But you obviously have made your mind up. Just please
- don't promote your poor programming practices on naive new programmers!


I haven't made my mind up.
I can live easily with both approaches as I told you.
The problem is you seem to think for some reason the object-oriented
approach of delivering a connection is superior, which is not true.

Please remember that we are NOT talking about globals as in ASP
(Application), but just globals for the duration of the script.

Yes, I know EXACTLY what we're talking about!


So please explain all the fuss you make.
I haven't seen any argument yet.
(I am serious)


Citrus's design is much better. There is a little overhead - but not
all that much.

Yes, Citrus claimed the same.
Also without any argumentation that made any sense.

If you are so sure of the superiority of the Object approach, why can you
not tell us why?


I tried. You obviously aren't listening!


I responded in the earlier thread with to your and citrus' claims, but you
didn't bother to respond yourself.
Get a mirror man.
It is you who isn't listening.


And I find objects almost always improve the structure of my code. It
also makes it more flexible and configurable. For instance - I can
easily change databases simply by changing the database object. No
changes in my code are necessary.

No changes in your code needed?
Of course you need to change something in your code, the Object that
makes the connection is changed by you.


No, the OBJECT code changes. MY CODE does not!


Aha, now I get it.
The Objectcode is not part of the application in your view?

Get real.

Now compare this to an include that delivers the connection: I also have
1 place to change the connection, and it is included everywhere.
Then everywhere where 'global $connection;' is used, the connection is
up-to-date.

Don't try to sell nonsense to me.
I developed years and years in Java, and do not fall for laymans
arguments.

I've been programming since 1967 (in Fortran I). I've written C++ for 18
years, some of them as a programmer for IBM. I've been writing Java for
over 10 years. And since then I've been a successful consultant,
writing code and managing projects.

Hardly a layman.


Ok, great credentials.

Now show them off and write a decent response.

Another thing: In PHP Objects are only halfhearted and last only for the
duration of the script. They are not persistent. (Unless of course you
serialize and deserialize them from script to script, but that is not
exactly persistent.)


So? The same is true for any program!


Nonsense.
In Java Objects happily exist in memory (or swapped for that matter) for
months and months.
If memory servers me well I have a few around for some years now.

PHP has to serialize them, generating a string, and revive them where
needed.
Really, that IS something else than being in memory and in-process.
PHP is not really OOP. They just added the possibility to use objects. Good
move by the way.

Object in PHP are nothing more than a bundling of some functions
together, and their own namespace. Really that is all there is to it.

And you obviously don't want to understand.


Well....

Where did I hear that before?
Hmm, let me see....
I remember! It was some guy telling me I could find peace if I followed his
God. Yeah that was it.
I asked him why I should follow his God while so many others are around too.
I didn't want to listen, so he told me.

Well, I DO listen. Give me something reasonably to think about!
Don't try to make more of it than that.
Heck - I can even use flat files when
necessary!
So can I, but what has that to do with this issue?
Are you suggesting that Objects are the next step in evolution of the
$connection in scripts? Haha.


The fact is - I can do it without any changes to my code!


We have been over that before.
You DO have to change your code, how else will the object know its
connectstring or databaseserver or whatever changed?

When using a connection that is included above every php-script you also
have only 1 place to change that.

Really, I do not see any advantage here.
If you do, tell me.

Regards,
Erwin Moller


But this conversation is at an end. I don't argue with close-minded
idiots.


As you can see: I DO agrue with idiots.

Here's a tag line for you:

"My mind is made up. Don't confuse me with the facts!"


Sounds very kinky and cool, really!
The kind of line you can use everywhere to make your argument sound more
worthwhile. Readers Digest?

Erwin
Feb 1 '06 #8

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

Similar topics

0
by: yzzzzz | last post by:
Hi, I am compiling PHP 5.0.2 myself with MySQL support. I did a ./configure --with-mysqli=/usr/local/mysql/bin/mysql_config (see end of post for complete configure) Note: I also have...
0
by: Roy Shaw | last post by:
When configuring PHP5 (5.0.3) to use the mysqli libraries I get a "No such file or directory" from the configure script. My goal is to get PHP5 running with mysql 4.1.09 with both the mysql and...
2
by: ojorus | last post by:
Hi! Some questions regarding the mysqli-extension (php5) 1) Prepared statements: If I understand things right, prepared statements will give better performance if you make several similar...
12
by: davids58 | last post by:
trying to figure out how to use a mysql database with PHP. I ran the following code: <?php // defines database connection data define('DB_HOST', 'localhost'); define('DB_USER', 'ajaxuser');...
2
by: Curtis | last post by:
Hello everyone: Recently, I decided to upgrade to PHP 5.2.0. I have C:\php5 in the Windows XP PATH, so upgrading is quite painless; just unzip new release, and restart Apache! Usually it goes...
13
by: Schmidty | last post by:
If you do a page reload with $_SERVER will your program lose a mysqli connection upon the reload of the page? Would this code work? I need to know how to carry over a connection between methods as...
2
by: Curtis | last post by:
Hello everyone: I have come to love the ease of updating PHP, since getting used to using it these past few years. Recently, however, when I upgraded from PHP 5.1 to PHP 5.2.0 and again when...
21
by: Daz | last post by:
Hi everyone. I am trying to create an extension of the mysqli class within PHP, and I am finding it quite difficult. I am fairly new to PHP classes, and decided to give them a go. Here's what I...
2
by: webcm123 | last post by:
People say that structural programming isn't good for database connection. I code fast-running structural oriented CMS and I don't know what I should do. I use mysql connection using mysql_*. I...
2
by: Michael | last post by:
Hi, I try to use mysqli object instead of standard mysql functions. Is it ok to create mysqli object within my class or schould I pass mysqli object to my object. The problem is, with code...
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
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:
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.