如题,出现错误。fatal error: call to a member function query() on a non-object in d:\www\2shou\class\bulletin.php on line 47
代码如下:
conn = mysqli_connect(localhost, root, pass, 2shou);
mysqli_query($this->conn, set names gbk);
}
function __destruct() {
// 关闭连接
mysqli_close($this->conn);
}
// 获取公告信息
function getbulletininfo($bid) {
//设置查询的select语句
$sql = select * from bulletin where id=' . $bid . ';
// 打开记录集
$results = $this->conn->query($sql);
// 读取公告数据
if($row = $results->fetch_row()) {
$this->id = $bid;
$this->title = $row[1];
$this->content = $row[2];
$this->posttime = $row[3];
$this->poster = $row[4];
}
else {
$this->id=0;
}
}
// 获取所有公告信息,返回结果集
function getbulletinlist() {
//设置查询的select语句
$sql = select * from bulletin order by posttime desc;
$results = $this->conn->query($sql);
return $results;
}
// 获取所有公告信息,返回结果集
function getrecentbulletinlist() {
//设置查询的select语句
$sql = select * from bulletin where datediff(day, getdate(), posttime) $results = $this->conn->query($sql);
return $results;
}
// 添加公告信息
function insert() {
$sql = insert into bulletin (title, content, posttime, poster) values (' . $this->title . ',' . $this->content . ',' . $this->posttime . ',' . $this->poster . ');
// 执行sql语句
$this->conn->query($sql);
}
// 修改公告信息
function update($bid) {
$sql = update bulletin set title=' . $this->title . ', content=' . $this->content . ', posttime=' . $this->posttime . ', poster=' . $this->poster . ' where id= . $bid;
// 执行sql语句
$this->conn->query($sql);
}
// 批量删除公告信息
function delete($bid) {
$sql = delete from bulletin where id in ( . $bid . );
// 执行sql语句
$this->conn->query($sql);
}
}
?>
回复讨论(解决方案) 你在构造函数中
function __construct() {
// 连接数据库
$this->conn = mysqli_connect(localhost, root, pass, 2shou);
mysqli_query($this->conn, set names gbk);
}
所以 $this->conn 是资源
但你在其他方法中却用 $results = $this->conn->query($sql); 进行访问
那么 $this->conn 什么时候又变成对象了呀?
所以构造函数应写作 function __construct() { $this->conn = new mysqli(localhost, root, pass, 2shou); $this->conn->set_charset('gbk');}