致命错误:未捕获错误:调用未定义的方法Database :: query()

时间:2018-09-22 19:25:44

标签: php mysql

我知道由于方法的作用域而导致错误,并且未在其中定义变量$ conn。如何在第二个类中定义该受保护变量,以便可以连接到数据库和获取数组。

class Config{
private $host;
private $user;
private $pass;
private $db;
protected $conn;

// open connection to database
 public function __construct() {
    $this->db_connect();
  }

 static public function db_connect(){
    $host = '';
    $user = '';
    $pass = '';
    $db = '';

    $conn = new mysqli($host, $user, $pass, $db);
    if(mysqli_connect_errno()){
  $msg = "Database connection failed: ";
  $msg .= $conn->connect_error;
  $msg .= " (" . $conn->connect_errno . ")";
  exit($msg);
    }
 }
 }

我的第二堂课

 class Database extends Config{

 public function __construct(){
 parent::__construct();
 }

 static public function find_by_sql($sql){
  $result = $conn->query($sql);
  if(!$result){
   exit("Database query failed.");
 }

//gather result into objects
$object_arr = [];
while($record = $result->fetch_assoc()){
  $object_arr[] = htmlentities($record);
}
// result object method to free result set
$result->free();
}

}

现在使用

 Config::db_connect();
 $sql = "SELECT * FROM Events ";
 $event = Database::find_by_sql($sql);

 echo '<pre>';
 echo print_r($event);
 echo '</pre>';

0 个答案:

没有答案