【发布时间】:2012-04-01 02:30:19
【问题描述】:
当我上传到实时服务器时,我遇到了以下错误。它在我认为很奇怪的本地主机上工作正常。
致命错误:在非对象上调用成员函数 close()....
它所指的线
$stmt->close();
与数据库的连接
$connection=new mysqli($MYSQL_HOST,$MYSQL_USER,$MYSQL_PASS,$DB)or die(mysqli_error($connection));
类本身。
function getTimes(){ //this method just pulls the results of the query and returns them as an array
global $connection;
$route = $this->route;
$station = $this->station;
$day = $this->day;
// create a prepared statement
if ($stmt = $connection->prepare("select time from timetable where route=? and day=? and station=?")) {
$stmt->bind_param("sss", $route, $day, $station); // bind parameters for markers
$stmt->execute(); //execute query
$stmt->bind_result($col1); //bind result variables
while ($stmt->fetch()){
$results[]=$col1;
}
}
$stmt->close();//close statement
return $results;
}
【问题讨论】:
-
看起来 $connection->prepare() 由于某种原因失败了。如果它返回 false 则 $stmt 为 false,而不是您预期的 mysqli 对象。
-
您的 $connection 也有可能为空,而您没有检查它。但这不是你目前的错误
-
@Churk 这将导致致命错误:在非对象上调用成员函数 prepare()。无论哪种方式,我都同意您应该将连接作为参数传递:
function getTimes(mysqli $connection) {} -
@cbuckley 数据库单例会比将连接作为参数传递给需要数据库的每个函数更好(更易于维护)。喜欢
$connection = myDatabase::getInstance(); -
@MrCode 我从来没有实现过单例,这很容易让我明白吗?我才刚刚开始从程序 php 转向 OOP PHP