![](/img/trans.png)
[英]PHP Fatal error: Uncaught Error: Call to a member function prepare() on null
[英]PHP Fatal error: Call to a member function prepare()
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致命错误:在第58行的/home/pipedu/public_html/msgbrd/class/DBTransaction.php中,在null上调用成员函数prepare()
我在哪里弄错了。 当我在localhost上运行它时,它工作正常。
您所设置的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.