How can I make a mysql connection inside a function if my mysql connect is in another include file?
Here is the mysql connect include file.
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
}
File: DB.php
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
function getConnection() {
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
} else {
return $dbc;
}
}
Other file:
require_once '/path/to/DB.php';
$connection = getConnection();
var_dump($connection->host_info);
you could make $dbc global inside the function.... as long as both files are included it should work fine
@powtac:
I agree on a per case basis, however if you plan on making a more robust database solution for a large site, having one class object (well named is important) can be a powerful tool. That's not to say you couldn't do the same thing and make the object a static variable inside of a function to prevent a careless developer from overwriting it:)
Since you might be calling getConnection
a lot, it makes sense to make it static
so that it does not get created more than once. Building on powtac's version:
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
function getConnection() {
static $dbc;
if (!$dbc) {
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL.', E_USER_ERROR);
}
}
return $dbc;
}
You would then include this file and call getConnection
wherever it's convenient.
Apart from making $dbc
static
so that it's only created once, I also removed the MySql error message when a connection cannot be established (it's generally a good idea to not give out such information if your users might see it; errors on connect at development time are relatively rare and can be debugged easily on the spot). Finally, I left the trigger_error
and did not replace it with the more usually seen die
because it might be part of your error handling framework. However, I did raise the error severity to signify that an error when attempting to connect should be an immediate show-stopper.