這就是這種情況。我在3個PHP文件,都在同一個項目文件夾:在PHP中使用準備好的語句時發生致命錯誤
- constants.php
- Mysql.php(類)
- 的index.php
當我運行的index.php,我得到:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\MyBlog\MyClass\MySql.php on line #
constants.php:
<?php
//Define constent her
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'myblog');
Mysql.php:
<?php
require_once 'constants.php';
class MySql{
private $conn;
protected $_query;
function __constructert() {
$this->conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or
die("There was a probelm connecting the database");
return $this->conn;
}
protected function _prepareQuery()
{
//her the line that problem come from beetwen the() of if :
if (!$stmt = $this->conn->prepare($this->_query)) {
trigger_error("Problem preparing query", E_USER_ERROR);
}
return $stmt;
}
protected function _dynamicBindResults($stmt){
$meta=$stmt->result_metadata();
while ($field = $meta->fetch_field()) {
print_r($field);
}
}
function query($query){
$this->_query = filter_var($query,FILTER_SANITIZE_STRING);
$stmt = $this->_preparequery();
$stmt->execute();
$results=$this->_dynamicBindResults($stmt);
}
的index.php:
<? PHP
include 'MySql.php';
$Db= new MySql();
$Db->query("select * from status");
正如我所說的,當我運行的index.php,我得到這個:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\MyBlog\MyClass\MySql.php on line
這條線是:
if (!$stmt = $this->conn->prepare($this->_query)) {
欲瞭解更多信息,我測試了與數據庫的連接,沒關係。我測試了_query
屬性是否採用SQL語句,並且它的確如此。