We help IT Professionals succeed at work.

PHP MYSQLI Connection in Function in a class

AlexPonnath asked
Last Modified: 2017-05-16
i am trying to start moving all my actual mysql code in php to a separate class file so its easier to read and files get smaller. I am using classes and functions. My question now is what is the best way to create the actual mysql connection which i can use in the functions.
class FileUpload{

public static function loadLogin(){
 $db = new mysqli('mysql.local', 'test_user', 'test', 'my_db');

if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
$sql = "select UserId , Password , Spid FROM tbl_nanpa_login where active = 1";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');

while($row = $result->fetch_assoc()){
return $UserData;


Open in new window

I want to avoid having to place the connection part in each function of the class
Watch Question

Most Valuable Expert 2017
Distinguished Expert 2019
Unlock this solution and get a sample of our free trial.
(No credit card required)
Most Valuable Expert 2011
Author of the Year 2014

No matter how many times we ask Experts-Exchange to help questions by searching the Articles for matching keywords from the questions, they seem unable to get it right.  So, going forward, before you bother to post a question at Experts-Exchange, make your own search for the keywords in the Articles.  You'll be surprised how many questions have been asked and answered in the Article library!

Here's an article on dependency injection.  It is a core principle of modern application design.


Ray, if my question bothers you don't answer that simple.. and since i did not know about Dependency Injection its hard to search for.
Most Valuable Expert 2011
Author of the Year 2014

Alex, I understand.  That is why we are showing you dependency injection.  It's a term of art, but it's really an easy concept.

What I hope for Experts-Exchange is that one day they will find a way to make it easier for us to find information like this -- where we don't have the exact word, but we have some of the concepts.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.