/    Sign up×
Community /Pin to ProfileBookmark

Global MySQL connection for use with objects

I’ve just dipped my hands into the more hardcore OOP aspects of PHP… including using the mysqli class as opposed to just the mysql functions.

Anyways, I was just wondering if it is at all possible to have a sort of superglobal mysqli instance that can be referenced from within any other class without having to global it, or send it through an argument to __construct… anyone know if this is possible?

to post a comment
PHP

14 Comments(s)

Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — the closest you can do is a pconnect, but those are not recommended. Why do you want to do something like this though?
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — Well I want to be able to more easily integrate different PHP classes I've written into applications simply by including the file... without worrying about globalizing the MySQL connection (and therefor having to modify the class with the object's variable name).

Also, globaling just seem inconvenient to me, I'm not sure way. Are you absolutely positive there isn't another way?
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — I still don't know what it is you're trying to do.
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — Okay, so, I've written/am writing several classes in OOPHP that I want to be able to use in any PHP application I write, without excessive tweaking. This includes classes like User (for controlling users of a website/application). However, most/all of these classes will require a MySQL connection in order to do their thing (in the case of the User class, the 'thing' would be adding/editing users in a mysql databse). Of course, the only way to do this within the class would be to globalize an existing MySQLi object or send one through an argument for the class in question (or creating a new one, but of course, that wouldn't be practical).

I want to know if there is a simple way to establish a MySQL connection and freely use that connection without referencing the original MySQLi object. For example:[code=php]// establish mysql connection out here somewhere
class User {
function getUser($id) {
mysqli::query(...sql...); // of course this doesn't work because mysqli::query is not static
}
}
User::getUser(10);[/code]
This probably just confused you more, but I can't really think of a way I could be more clear... sorry.
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — and what's the problem with just including the class file and instantiating a new object when needed? i'm not sure why you think that you need to globalize something, as a new instance gets created on each page sent from the server.
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — No no no, I need to globalize the MySQLi connection object so that it can be used from within OTHER classes.[code=php]$mysqli = new mysqli('localhost', 'username', 'password');

class User {
function getUser($id) {
// cannot run query from here, because $mysqli cannot be acccessed from here
}
}[/code]
I just want a mysqli object to be a superglobal, pretty much, so I won't have to...[code=php]global $mysqli;[/code] whenever I want to use it within a function or class.
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — If you feel that you need to do that, I don't think you have a strong grasp of object oriented programming.
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — If you feel that you need to do that, I don't think you have a strong grasp of object oriented programming.[/QUOTE]I never said I did... atleast, not PHP OOP. Could you please explain HOW I would query a MySQL DB from within a class, then?
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — Now that I understand what you're trying to do, there are two approaches I would recommend.

1) make a mysqli object as a parameter of each type of object (class) you want to create. This method would create code that is less reusable.

2) have a common mysqli object that you use to generate all of your database interaction. this would be a more traditional approach. would look something like:

[code=php]
include("/path/to/your/personal_mysqli.php");
$bob = new personal_mysqli(/*any parameters can go here*/);
$bob->prepQuery($sql);
//etc...
[/code]


Most people don't call mysqli directly. It's usually embedded in a lower level.
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — Alrighty, I've put together a little example to better illustrate my situation. This example uses your method #1, which is the one I understand ? Could you show it how it would be done with your second method?[code=php]<?php
class User {
function __construct($mysqli) {
$this->mysqli = $mysqli;
}
function getUserById($id) {
$this->mysqli->query('select * from users where id = '.$id.' limit 1');
}
}
class Article {
function __construct($mysqli) {
$this->mysqli = $mysqli;
}
function getArticleById($id) {
$this->mysqli->query('select * from articles where id = '.$id.' limit 1');
}
}
$mysql = new mysqli('localhost', 'username', 'password', 'database');
$user = new User($mysql);
$user->getUserById(10);
$article = new Article($mysql);
$article->getArticleById(4);
?>[/code]
Thanks for your help so far ?
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — what you're creating there is very specific to one case and only one case. for one, you're never defining the parameters of the class. you're also doing this very procedurally, while using object oriented syntax you're making calls as if it's just one after another. you don't have a full working example here.

what i'd recomment is create a class based on what mysqli has. build it based on what you need. those "objects" you're calling article and user, aren't really objects anything outside of mysqli. you're defining them as instances of the mysqli object only and they have one purpose only. what happens when your articles or users table changes name?
Copy linkTweet thisAlerts:
@Daniel_TauthorApr 19.2006 — Alright, clearly I have more to learn... the problem is, all the tutorials that I've found on the subject only cover the bare basics of OOP... where would you suggest I learn?
Copy linkTweet thisAlerts:
@Stephen_PhilbinApr 19.2006 — I didn't learn from any place in particular, I was lucky enough to have the opportunity to talk to people that make games and things like that on a daily basis for a living, I just picked up small tips from them and keep a few simple rules/guides in mind.

The first thing is, like chazzy suggests, donn't make anything too specific. Not in your core classes at least anyway. Try to make your most used classes (such as database interaction and the actual user object its self) as generic as possible. That way you will be able to re use most (if not, all) of your other code. It doesn't matter if these core classes don't do everything that you need the end object to do because...

Classes can be extended to add functionality and increase reusability. For example, think of a 3D video game with good guys and bad guys (it's a classic). The good guys and the bad guys might be very different for the most part, but they both have something in common; They're both guys.

If you were to make a good_guys class and a bad_guys class and nothing else, then you'd probably have met the requirements to make them both, but for just those character types and just for that game. A preferable alternative would be to make a base class "guys" that has just the fundamentals that are common in all guys, and then extend that class with small extending classes that finish off the tailoring to make them a full fledged good guy or a bad guy. It also leaves you with a class that you can use to make other types of guys in the game with little extra coding. Like the neutral guy that just wants to get home in time for tea, for example. You could probably also use it in other games too, becasue it'd just have the bare essentials like the characters name and other things that just about every "guy" would.

Oh and remember to try and think in terms of objects interacting with other objects and/or the members of objects, rather than setting out one specific rule after another. Try to think of it like lego. The bricks are always the same basic generic bricks. They only become something when you put them together. What they become depends on how they were put together, not how they were made.
Copy linkTweet thisAlerts:
@chazzyApr 19.2006 — Have you read the set of articles that start with this one?

http://www.developer.com/lang/php/article.php/3302171

It's the first one that I found that wasn't covered with people saying "this has bad practices/incorrect terminology/syntax"
×

Success!

Help @Daniel_T spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...