This is because you have to use include("configuration.php");
not include_once("configuration.php");
If you include_once
, it will only work when the first instance of this configuration file is included in the script somewhere.
I would suggest making a class to wrap your connection saving it to a singleton state for use everywhere else in your script. Here is a simple example:
classes/class.DatabaseConfig.php
<?php
class DatabaseConfig
{
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
public function connect($host = "localhost", $username = "username", $password = "password", $database = "database")
{
// Create connection
try {
$mysqli = new mysqli($host, $username, $password, $database);
return $mysqli;
} catch (mysqli_sql_exception $e) {
throw $e;
die();
}
}
}
classes/class.Db.php
<?php
class Db
{
private static $singleton;
public static function mysqli()
{
if(empty(self::$singleton)) {
$con = new DatabaseConfig();
self::$singleton = $con->connect();
}
return self::$singleton;
}
}
index.php
<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// This will work
$con = Db::mysqli();
function myQuery()
{
// This will also work, so long as you have included the class
// file once before this function (not necessarily in this function either)
// is called to use
$con = Db::mysqli();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…