Is it ok to define PDO db connection in function?

I am thinking, is it safe and OK to use db connection in function to return it anywhere in the project? If I want to reuse this project to build another one, I can change db connection only in this function and I don't need to go all over the script searching and changing connection parameter.

function connect_db(){
$db = new PDO('mysql:host=localhost;dbname=;charset=utf8', '', '');
return $db;
}

Now I can call it anywhere functions.php file is required once, by returning

$db = connect_db();

and then whatever statement follows.

Is it ok and safe?

And how to close connection like this at the end of the page?

 $db = NULL;

apparently won't work.

Answers


Yes, it is safe and ok to have a single place that creates a connection to your database. I would change your function just a bit though:

<?php
function connect_db(){
    try{
        return new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND =>'SET NAMES utf8'));
    }catch (PDOException $e){
        echo '<p>Error connecting to database! ' . $e->getMessage() . '</p>';
        die();
    }
}
?>

You can read more about the PDO constructor in the documentation.

And to close the PDO connection created this way you do indeed just:

<?php
$pdo = NULL;
?>

Please note that there is really a lot more to be said on this subject. Ideally you would have a class that handles the creation of your PDO object(s). You might want to take a look at this excellent answer from Gordon as a place to start.


Need Your Help

XML schema file (.xsd) has different size on Linux and Windows

xml linux windows file schema

I have a XML schema file (.xsd) and it is showing different size on Linux and Windows. What can be the reason of it?

Modifying existing built-in phone application

android telephony telephonymanager rom

Instead of building my own custom telephony application by making use of the TelephonyManager class, is it possible to modify the built-in native phone application on a Google Nexus 4 or 5 device t...