We help IT Professionals succeed at work.

PHP MYSQLI Connection in Function in a class

AlexPonnath
AlexPonnath asked
on
625 Views
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 . ']');
}
$UserData=array();
$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 . ']');
}

$y=0;
while($row = $result->fetch_assoc()){
$UserData[$y]['UserId']=$row['UserId'];
$UserData[$y]['Password']=$row['Password'];
$UserData[$y]['Spid']=$row['Spid'];
$y++;
}
return $UserData;

}
}

Open in new window


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

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

Commented:
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.
https://www.experts-exchange.com/articles/19999/PHP-Design-Avoiding-Globals-with-Dependency-Injection.html

Author

Commented:
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

Commented:
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.

OR

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.