PHP:无法调用连接对象

时间:2017-09-10 12:03:16

标签: php mysql

我是PHP编程的新手。我创建了一个配置和一个脚本来打印我所有的MySQL数据库信息。这是我的配置:

class DbManager{
protected $dbh;
public $dbhost = '127.0.0.1';
public $dbname = 'bookstore';
public $dbuser = 'root';
public $dbpass = '';

public function getConnection(){
    try{
    $dbh = new PDO("mysql:host=$this->dbhost;dbname=$this->dbname", $this->dbuser, 
    $this->dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;            
    }
    catch(PDOException $e){
        echo "Error : " . $e;
    }

}

} 并且,这是我获取数据库信息的脚本:

require_once('config.php');
class ShowData extends DbManager{
  public function getInfo(){
    $dbh= getConnection();
    $smt = $dbh->prepare("SELECT * FROM books");
    $smt->execute();
    $result = $smt->fetchAll();
    echo "<pre>";
    print_r($result);
  }
}

我收到错误:Fatal error: Uncaught Error: Call to undefined function getConnection()。 我无法创建一个连接变量,通过它我可以进行SQL查询。我怀疑$dbh= getConnection()。我的查询是否正常?

1 个答案:

答案 0 :(得分:3)

您的getConnection已上课,因此您需要拨打$this->getConnection()

class ShowData extends DbManager{
  public function getInfo(){
    $dbh= $this->getConnection(); // change this line
    $smt = $dbh->prepare("SELECT * FROM books");
    $smt->execute();
    $result = $smt->fetchAll();
    echo "<pre>";
    print_r($result);
  }
}