Asperger
Asperger

Reputation: 3222

PHP : Make other functions access the $conn variable inside my database connection function

Make other functions access the $conn variable inside my database connection function

So here I am absolutely desperate trying to make something work. I know what im trying to do is not OOP neither 100% best practice. It is not for a live website, I am just learning some basic PHP concepts on XAMPP.

What I am trying to do is to make the $conn variable inside my database connection function accessible to all other functions that need it. I am thinking of passing it as a parameter, but how can this be done? I prefer not using PHP's "global" or $GLOBALS. My method of working right now is with mysqli using procedural methods.

For example I have something like this:

function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}

function someFunction () {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}

I never found the answer to my issue...most solutions which I recently got familiar with are OOP based or use somewhat questionable methods.

------------------------------------------------------------------------------------------------------------------------------------

SOLUTION A - I would rather avoid not having my connection in a wrapper and using global variables:

global $conn = mysqli_connect ("localhost", "root", "", "database");
global $conn;

function someFunction () {
global $conn;
$result = mysqli_query ($conn, "SELECT * FROM examples)
}

SOLUTION B - I am not ready for OOP yet but I know this works. The point is I want to learn something different:

class Database
{
    private static $conn;

    public static function getObject()
    {
        if (!self::$conn)
            self::$conn = new mysqli("localhost", "root", "", "database");

        return self::$conn;
    }
}

function someFunction () {
$result = mysqli_query (Database::$conn, "SELECT * FROM examples)
}

SOLUTION C - Not using functions at all...just keeping it unwrapped which I dont find very practical in the long term:

$conn = mysqli_connect ("localhost", "root", "", "database");

$result = mysqli_query ($conn, "SELECT * FROM examples)

------------------------------------------------------------------------------------------------------------------------------------

THE SOLUTION I AM TRYING TO ACHIEVE:

function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
return $conn;
}

function someFunction () {
$conn = db ();
$result = mysqli_query ($conn, "SELECT * FROM examples)
}

OR Something like this where I just pass in the connection as a parameter or something (pseudo code at the moment)

function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}

function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}

------------------------------------------------------------------------------------------------------------------------------------

So how do I achieve something like the last two but which actually works. Is this concept possible?

Upvotes: 16

Views: 32643

Answers (5)

Fakhar Anwar
Fakhar Anwar

Reputation: 295

All of the answers in this section are overkill as they are doing overhead just by creating a wrapper around a database object. For separation of concern(Maintainability) use a separate PHP file for database connection and use require_once.

//Inside Database_Connect.php

$db = mysqi_connect(localhost, database, password);

Now use $GLOBALS['db'] inside your mysqli_ functions wherever needed.

OR, initialize your script / object as

$dbConn = $GLOBALS['db'];

and use $dbConn inside your mysqli_ functions wherever needed.

Upvotes: 2

Reed
Reed

Reputation: 14984

Your Desired Solution: This should work, and you'll only make one connection.

function db () {
    static $conn;
    if ($conn===NULL){ 
        $conn = mysqli_connect ("localhost", "root", "", "database");
    }
    return $conn;
}

function someFunction () {
    $conn = db();
    $result = mysqli_query ($conn, "SELECT * FROM examples);
}

If you used the function someFunction($conn), that would make your code much messier, since you wouldn't actually have universal access to $conn from anywhere.

You should go with Solution B IMO. That way, you can have simple access to it Database::$conn which will be consistent throughout your script. You could should have an initialize function (you could use a different name if you want) that will initialize Database::$conn, and you can then use that to initialize other things on the Database class later, if desired.

Solution A is terrible. I did that for a long time (globalizing things), and it was a horrible idea. I should have never done that. But I did. And I learned. It just made code get progressively sloppier and sloppier.

Solution B: Database::$conn should be public if you want to be able to access it by Database::$conn from anywhere. If it's private, then you would always need to call Database::getObject();

Solution C: You're right. That would be very impractical.

Solution B rewrite:

class Database
{
    /** TRUE if static variables have been initialized. FALSE otherwise
    */
    private static $init = FALSE;
    /** The mysqli connection object
    */
    public static $conn;
    /** initializes the static class variables. Only runs initialization once.
    * does not return anything.
    */
    public static function initialize()
    {
        if (self::$init===TRUE)return;
        self::$init = TRUE;
        self::$conn = new mysqli("localhost", "root", "", "database");
    }
}

Then... call Database::initialize() at least once before it gets used.

<?php
Database::initialize();
$result = mysqli_query (Database::$conn, "SELECT * FROM examples);
?>

EDIT

  • You can also call Database::initialize() immediately after the declaration of the class, in that PHP file. Then initializing is handled.
  • I'm now far more fond of something like Database::getDb() than accessing the $conn property directly. Then initialize can be called from the getDb() function. Basically like the Desired Solution but inside a class. The class really isn't necessary, but it can be nice if you like classes, like I do.

Upvotes: 25

Hassan Saeed
Hassan Saeed

Reputation: 7110

simple answer just pass your $conn variable into another calling function(instead of making new connection)

like

yourpage.php

$conn = new mysqli($servername, $username, $password, $dbname);
someFunction ($conn)//you can add other parameters if you like 

function someFunction ($conn) {
    $result = mysqli_query ($conn, "SELECT * FROM examples);
}

Note:This is not good practice to always make new connection for database access.so always make connection once and use it every where.(but if your requirement different and require multiples connections then you can make multiples connections)

Upvotes: 0

Subin Thomas
Subin Thomas

Reputation: 1416

If you have multiple php files which require db access, then the option you can have is create a file connection.php with connection code

<?php
$conn = mysqli_connect ("localhost", "root", "", "database");
?>

And use include_once 'connection.php'; in all other files you require a connection.

Upvotes: -1

s3nzoM
s3nzoM

Reputation: 2207

Pass an argument to your function like and return the connection

function db($conn){
   $conn = mysqli_connect ("localhost", "root", "", "database");
   return $conn;
}

Upvotes: -1

Related Questions