Ben Thompson
Ben Thompson

Reputation: 4833

Passing MySql connection in php

I have tried putting a mysqli connection script into a php function that various php files can call to connect to the database. I have created the following function:

public function connectToDatabase() {

    $con = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);

    echo "<br><br>";

    if (mysqli_connect_errno($con)) {
        echo "Failed to connect to MySQL:" . mysqli_connect_error();
    } else {
        echo "Connection successful";
    }

    return $con;
}

I then call that function from another file using (the above file has been included):

$con = connectToDatabase();

However, while the code in the top function works fine, passing the connection in the variable $con doesnt seem to work. It has occured to me that the connection is closing automatically when it reaches the return statement. Is this the case? If so, how can I stop that?

Many thanks

Upvotes: 1

Views: 292

Answers (1)

Steven Moseley
Steven Moseley

Reputation: 16325

While your issue has been answered in the comments, better to structure your connection as a Singleton class, so you're not opening multiple instances of your connection throughout your code:

class DatabaseConnection {

    const HOST     = 'localhost';
    const USERNAME = 'not_root';
    const PASSWORD = 'not_blank';
    const NAME     = 'your_db';

    private static $_instance;

    // Private constructor prevents instantiation
    private function __construct() {
    }

    public static function getInstance() {
        if (!self::$_instance) {
            self::$_instance = mysqli_connect(self::HOST, self::USERNAME, self::PASSWORD, self::NAME);
            if (mysqli_connect_errno(self::$_instance)) {
                throw new Exception("Failed to connect to MySQL:" . mysqli_connect_error());
            }
        }
        return self::$_instance;
    }
}

Then, call it like this:

try {
    $con = DatabaseConnection::getInstance();
} catch (Exception $e) {
    // Handle exception
    echo $e->getMessage();
}

Upvotes: 1

Related Questions