class DBconnection {
protected $connection;
public function __construct(){
$this->dbConnect();
}
public function dbConnect() {
try {
// Try and connect to the database, if a connection has not been established yet{
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file("config.ini");
$dsn = 'mysql:host='. $config['host'] .';dbname=' . $config['dbname'] . ';charset=utf8;';
$this->connection = new PDO($dsn, $config['username'], $config['password']);
//echo 'Connection to database has been successfull!';
return $this->connection;
} catch(Exception $e) {
echo 'There was an error while connecting to the database!';
$this->connection = NULL;
}
}
public function disConnect(){
$this->connection = NULL;
//echo '<br>Database connection has been disconnected successfully!';
}
}
class DBTransaction extends DBconnection {
public function __construct(){
parent::__construct();
}
// FETCH ALL DATA
public function select_all($query) {
try {
$result = $this->connection->query($query);
$result->execute();
return $result;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
// FETCH SPECIFIC DATA
public function select_specific($query, $params = []) {
try {
$result = $this->connection->prepare($query);
$result->execute($params);
return $result;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
// EXECUTE INSERT, UPDATE, DELETE
public function execute_query($query, $params = []) {
try {
$stmt = $this->connection->prepare($query);
$stmt->execute($params);
return $stmt;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
The problem is I am getting this error:
PHP Fatal error: Call to a member function prepare() on null in /home/pipedu/public_html/msgbrd/class/DBTransaction.php on line 58
Where did I made a mistake. When I run this on localhost, it just works fine.
connectionisnull. - JeffdbConnectthe line$this->connection = NULL;is a mistake. If you can't properly handle the event of the connection failing then don't handle the exception at all and let it propagate so you can see that it failed. - apokryfos