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());
}
}
}
问题是我收到此错误:
PHP致命错误:在null中调用成员函数prepare() 第58行/home/pipedu/public_html/msgbrd/class/DBTransaction.php
我在哪里弄错了。当我在localhost上运行它时,它运行正常。
答案 0 :(得分:1)
您使用connection
在NULL
内的catch
区块中将班级的DBconnection::dbConnect()
属性设置为$this->connection = NULL;
。但是,在您的其他功能中,您不会检查它。不要因为而在你的班级中使其成为一个接受状态而引发错误。
您的解决方案是:
DBconnection->connection = NULL
会成为你班上的非法状态,你可以在其他方法中忽略这种情况。示例:
try {
$con = new DBTransaction();
$result = $con->select_all('SELECT * FROM table');
} catch (Exception $e) {
$result = NULL;
}
DBconnection->connection
在您的其他方法中NULL
可能public function select_all($query) {
if (this->connection === NULL) {
return NULL;
}
$result = $this->connection->query($query);
$result->execute();
return $result;
}
并返回并判断该案例的值:示例:
language