1

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

Ben Thompson
  • 4,743
  • 7
  • 35
  • 52
  • 3
    `connectToDatabase` !== `connectToDatabse` – bwoebi Jun 16 '13 at 09:57
  • [Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Your Common Sense Jun 16 '13 at 09:59
  • ...how embarrassing... – Ben Thompson Jun 16 '13 at 09:59
  • ok so I have edited the databAse typo, but still it doesnt work...? – Ben Thompson Jun 16 '13 at 10:03
  • @BenThompson First, try echoing out the value of the variable `$con` from that file itself. Then, find whether including the file throws any error. If you are in doubt, post the lines you used to include the php file. – Kevin Jun 16 '13 at 10:12

1 Answers1

1

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();
}
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50