PHP PDO-MYSQL:如何使用跨不同类的数据库连接 [英] PHP PDO-MYSQL : How to use database connection across different classes

查看:144
本文介绍了PHP PDO-MYSQL:如何使用跨不同类的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新的PDO与MYSQL,这里是我的两个文件:



我有一个连接类,我用来连接到数据库: p>

 类连接{

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\很抱歉,尝试连接到数据库时出错;
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;

}
}


}


b $ b

我在我的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的东西。
提前感谢。

解决方案

解决方案1 ​​

使用替换 class account_info {> class account_info extends connection {



替换

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

  $ info = new account_info(); 

它应该可以工作。



strong>解决方案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();

说明



作为一个好的规则:总是指定函数(public,protected或private)的scope关键字。



第一个解决方案称为继承,使用连接类扩展帐户类,以便从连接类继承所有方法和属性,并轻松使用它们。在这种情况下,你必须注意命名冲突。我建议你看看PHP手册中的类继承。



第二个解决方案称为依赖注入,它是一个非常鼓励的设计模式,使你的类在其构造函数中接受其他类,以便显式地定义类依赖关系树(在这种情况下,帐户依赖于连接,没有连接,我们不能使帐户工作)。



另一个,成千上万的可能的解决方案,将是一个人下面是一个称为Singleton的设计模式。然而,该模式最近被重新评估为反模式,不应该使用。


I'm kinda new to PDO with MYSQL, here are my two files:

I have a connection class that I use to connect to the database:

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);

    }
}   
}

I have an account_info class that i use to query the data from the database:

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;

    }
}       


}

I include both these files in my index.php page:

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

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

I just cant get it to work I'm not getting any output, I think it has something to do with the scope, but I don't know the correct why to fix it as I'm new to this PDO and OOP stuff. Thanks in advance.

解决方案

Solution 1

Replace class account_info { with class account_info extends connection {

Replace

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

with

$info = new account_info();

and it should work.

Solution 2 (suggested)

I highly suggest you to solve your problem with dependency injection in this case. Just replace your account class with:

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;
        }
    }       

}

and use it in index.php like this:

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

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

Explanation

As a general good rule: always specify the scope keyword for functions (public, protected or private).

The first solution is called inheritance and what we basically did was extending the account class with the connection class in order to inherit all the methods and properties from the connection class and easily use them. In this case you have to watch out for naming conflicts. I suggest you to take a look at the class inheritance in the PHP manual.

The second solution is called dependency injection and it is a wildly encouraged design pattern that makes your classes accept other classes in their constructor in order to explicitly define the class dependency tree (in this case account depend from connection and without the connection we can't make account work).

Another, of thousands of possible solution, would be the one that someone posted below which is a design pattern called Singleton. However that patter has been reevaluated recently as anti-pattern and should not be used.

这篇关于PHP PDO-MYSQL:如何使用跨不同类的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆