【发布时间】:2015-06-04 13:53:09
【问题描述】:
我很困惑我在下面的 php 代码中出错的地方。虽然,我在我的代码上看了很多次,但找不到为什么我会收到这个错误 'cannot access empty property' 。
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
此行出错:
$this->results = self::$conn->query($query) or die("数据库出错 连接".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';
【问题讨论】:
-
请用箭头或类似的方式指出您的错误行
-
请在发生错误的那一行显示错误和黑暗或评论
-
他也不需要这条线,因为连接会自动关闭。还有
real_escape_string($query)??不仅不推荐使用此功能,而且使用它的方式完全错误。 -
使用
self::conn而不是self::$conn。 -
$conn 是静态的,亲爱的。那么,我怎样才能只使用 self::conn