小编典典

PHP PDO-MYSQL:如何在不同类之间使用数据库连接

mysql

我对使用MYSQL的PDO有点陌生,这是我的两个文件:

我有一个用于连接数据库的连接类:

class connection{

private $host = 'localhost';
private $dbname = 'devac';
private $username = 'root';
private $password ='';

public $con = '';

function __construct(){

    $this->connect();

}

function connect(){

    try{

        $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
        $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);


    }catch(PDOException $e){

        echo 'We\'re sorry but there was an error while trying to connect to the database';
        file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);

    }
}   
}

我有一个account_info类,用于查询数据库中的数据:

class account_info{


function getAccountInfo(){

    $acc_info = $this->con->prepare("SELECT * FROM account_info");
    $acc_info->execute();

    $results = $acc_info->fetchAll(PDO::FETCH_OBJ);

    foreach ($results as $key) {
        $results->owner_firstname;

    }
}


}

我在index.php页面中都包含了这两个文件:

include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';

$con = new connection();
$info = new account_info();
$info->getAccountInfo();

我只是无法使其正常工作,我没有任何输出,我认为它与示波器有关,但是由于我是PDO和OOP的新手,所以我不知道为什么要修复它的正确方法。提前致谢。


阅读 336

收藏
2020-05-17

共1个答案

小编典典

解决方案1

替换class account_info {class account_info extends connection {

更换

$con = new connection();
$info = new account_info();

$info = new account_info();

它应该工作。

解决方案2(建议)

我强烈建议您在这种情况下使用依赖项注入来解决您的问题。只需将您的帐户类别替换为:

class account_info {

    private $con;

    public function __construct(connection $con) {
        $this->con = $con->con;
    }

    public function getAccountInfo(){

        $acc_info = $this->con->prepare("SELECT * FROM account_info");
        $acc_info->execute();

        $results = $acc_info->fetchAll(PDO::FETCH_OBJ);

        foreach ($results as $key) {
            $results->owner_firstname;
        }
    }

}

并像这样在index.php中使用它:

include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';

$con = new connection();
$info = new account_info($con);
$info->getAccountInfo();

说明

通常的规则是:始终为函数(公共,保护或私有)指定作用域关键字。

第一个解决方案称为继承,而我们所做的基本上是用连接类扩展account类,以便从连接类继承所有方法和属性并轻松使用它们。在这种情况下,您必须提防命名冲突。我建议您看一下PHP手册中的类继承。

第二种解决方案称为依赖注入,这是一种强烈鼓励的设计模式,它使您的类在其构造函数中接受其他类,以便显式定义类依赖关系树(在这种情况下,帐户依赖于连接,没有连接我们就无法使帐户正常运行)。

在成千上万的可能解决方案中,另一个是某人在下面发布的解决方案,该设计模式称为Singleton。但是,该模式最近已重新评估为反模式,因此不应使用。

2020-05-17