0

Is it safe to place my MySQL Database Connection inside a PHP Function so that other PHP functions can use it?

3 Answers 3

9

Yes. it is a good idea.

I even place mine in a class.

class database {

     protected $databaseLink;

     function __construct($mysql_db, $mysql_user, $mysql_pass, $mysql_dbName){
            $this->databaseName = $mysql_dbName;
            $this->database = $mysql_db;
            $this->mysql_user = $mysql_user;
            $this->mysql_pass = $mysql_pass;
            $this->openConnection();
      }

      function openConnection(){
            $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
            mysql_select_db($this->databaseName, $this->databaseLink);
      }

      function get_link(){
            return $this->databaseLink;
      }

}

Then you can just do:

 $db = new database('database', 'username', 'password', 'dbName');

 //to do a query:
 mysql_query("some query", $db->get_link());
Sign up to request clarification or add additional context in comments.

9 Comments

Is there a procedural style method?
I also put such a file outside of the web root and include it where needed, so my credentials aren't spit out if one way or another the PHP isn't parsed.
@pNUT, so you might be reduced to using functions. is there a reason for not using OOP?
@Neal The majority of my code is in procedural style and I'm not really knowledgeable on OOP yet.
E.g., if your webroot is /something/www/data/ I put the credentials in /something/www/db_account.php and then use something like require('../db_account.php'); where I want to connect to my DB.
|
1

You probably don't want to create it in a regular PHP function. If you will have multiple other functions accessing the db connection in the same script, remember that if you do something like

function get_db()
{
  $db = mysql_connect(...);
  return $db;
}

Then each time you call it, you will be creating and returning a new connection. It may be better to create it once per script inside a class as a Singleton, and have a class method return the database one connection to any function that calls it.

EDIT Neal's answer actually demonstrates the singleton pattern for this nicely. Beat me to it with a more code-complete answer.

Comments

0

It is a good thing for performance. Connecting to the database just when the function was called it will result a good performance for SQL server.

1 Comment

emmmm what? there could be many DB calls like that. that is never good

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.