情况就是这样。我创建了3个PHP文件,全部位于同一个项目文件夹中:
当我运行index.php时,我得到:
致命错误:在C:\wamp\www\MyBlog\MyClass\MySql.php行#中对非对象调用成员函数prepare()
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时,我得到了以下信息:
致命错误:在线调用C:\wamp\www\MyBlog\MyClass\MySql.php中非对象上的成员函数prepare()
这一行是:
if (!$stmt = $this->conn->prepare($this->_query)) {
要了解更多信息,我测试了到数据库的连接,没关系。我测试了_query
属性是否接受了SQL语句,并且确实如此。
发布于 2012-08-01 10:12:39
类MySQL
的构造函数名为__constructert()
;正确的构造函数名为__construct()
。
使用无效的名称,行$Db = new MySQL();
将创建对象,但构造函数不会被调用-因此永远不会创建MySQL连接/ $conn
对象。
发布于 2012-08-01 10:12:00
这里有一个错误,->_preparequery();
将其更改为:
function query($query){
$this->_query = filter_var($query,FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
$stmt->execute();
$results=$this->_dynamicBindResults($stmt);
}
https://stackoverflow.com/questions/11765049
复制