This question already has an answer here:
I built the database connection with Object static method. Then each function that gets data from database will connect the database first. however, in the second function call "get_us_states()", var_dump($db) is "NULL", but in the first function call "get_para_from_table_bank()", var_dump($db) is "object(PDO)#1 (0) { }". Can sb know why?
The code is below.
class Database_connection {
private static $dsn = 'mysql:host=localhost;dbname=xxx';
private static $user = 'xxx';
private static $pw = 'xxx';
private static $option = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
private static $db;
public function __construct() {}
public static function getDB () {
if (!isset(self::$db)) {
try {
self::$db = new PDO(self::$dsn,
self::$user,
self::$pw,
self::$option);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('../errors/database_error.php');
exit();
}
return self::$db;
}
}
}
function get_para_from_table_bank(){
$db = Database_connection::getDB();
$query = 'SELECT * FROM form_content_bank WHERE current_form = 1 ORDER BY orders';
try {
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
$statement->closeCursor();
return $results;
} catch (PODException $e) {
$error_message = $e->getMessage();
include('../errors/database_error.php');
exit();
}
}
function get_us_states(){
$db = Database_connection::getDB ();
$query = "SELECT * FROM us_states ORDER BY id";
try {
$statement = $db->prepare($query);
$statement->execute();
$us_states = $statement->fetchAll();
$statement->closeCursor();
return $us_states;
} catch (PODException $e) {
$error_message = $e->getMessage();
include('../errors/database_error.php');
exit();
}
}
function show_form(){
//get form content from database
$form_contents = get_para_from_table_bank();
***var_dump($db) in "get_para_from_table_bank()" is "object(PDO)#1 (0) { }"***
$us_states = get_us_states();
***var_dump($db) in "get_us_states()" is "NULL"***
... (other code)
}
show_form();
After call show_form function, always show "Fatal error: Uncaught Error: Call to a member function prepare() on null ", and I found when call "get_us_states()", the $db is NULL.
Can sb give me some suggestions?
</div>