Passing a db connection in function

Viewed 191

I have a database function and I am trying to figure out if passing the db info can be done in the same format as a new function

I was using a global db connect function but was told that is a bad practice so I wrote one of my functions as follows

function mysystem(mysqli $db){
  //mystuff here
}

and it connects to the database with no issue.

my 2nd function is a little different I created a function to check if anything duplicate exists

function check_duplicate_entries($table, $column_name, $value){

    $db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    $stmt = $db->prepare("SELECT * FROM $table WHERE $column_name = ?");
    $stmt->bind_param('s', $value);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();

    if (mysqli_num_rows($result) == 1) {
        return true;
    } else {
        return false;
    }
}

is there a way that I can pass my db info like the rest of my functions instead of calling a new db connection.

like this

function check_duplicate_entries(mysqli $db, $table, $column_name, $value){
1 Answers

Yes. It's common practice to use singleton pattern to handle this. This is code example for PDO, you can refactor it to mysqli

class MysqlConnector
{
    private static $connection;

    private function __construct()
    {
    }

    public static function getConnection(): PDO
    {
        $username = "root";
        $password = "";
        $database = "blog";
        $servername = "localhost";

        if (!empty(self::$connection)) {
            return self::$connection;
        }

        self::$connection = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
        self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return self::$connection;
    }
}

// now you can get your connection anywhere
// just make sure this class is available in your current namespace
$connection = MysqlConnector::getConnection();
$connection->query('SELECT COUNT(*) FROM articles');
Related