Pass PDO MySQL connection into function without global

Passing a PDO MySQL connection into a PHP function can easily be done, simply by assigning global to the PDO connection variable unless you want to be repeating the connection inside every function.

Using a global variable for the MySQL connection actually isn’t insecure its just rather opening up to issues if you re assign that variable elsewhere.

When there is another way to do something that can prevent these small issues you should take it. I myself are an avid user for a global connection variable in functions but i am changing that.

<?php
function db_connect()
{
    $host = '';
    $db_name = '';
    $db_user = '';
    $db_password = '';
    $db = "mysql:host=$host;dbname=$db_name;charset=utf8mb4";
    $options = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
    return new PDO($db, $db_user, $db_password, $options);
}

Just like that you can pass the PDO connection through to a variable like:

<?php
function get_data()
{
    $db = db_connect();
    $select = $db->prepare("SELECT data FROM `table`;");
    $select->execute();
    while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
        ///..............
    }
}

 

You can also give the connection parameters for occasions when you want to connect to different databases for some reason:

<?php
function db_connect($hostname, $database, $username, $password)
{
    $db = "mysql:host=$hostname;dbname=$database;charset=utf8mb4";
    $options = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
    return new PDO($db, $username, $password, $options);
}


function get_data()
{
    $db = db_connect('localhost', 'database', 'username', 'password');
    ///......
}

Or you can compress it:

<?php
function db_connect()
{
    $db = "mysql:host=localhost;dbname=database;charset=utf8mb4";
    $options = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
    return new PDO($db, 'username', 'password', $options);
}

Just like that there is no more global $db;.