0

I have the following database query which works fine but in another question earlier, it was brought to my attention that I'm using a global, when it's not necessary. The reason for that was that I attempted to use a protected variable but being a new-comer to OOP, was unable to make it work.

Perhaps someone could show me how it should be done?

<?
class DB {

  public function __construct() {

    global $dbh;

    try {
      $dbh  = new PDO('mysql:host=localhost;dbname=main_db', 'my_user', 'my_pass');
      $dbh  ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    catch(PDOException $e) {
      echo $e->getMessage();
    }
  }

  public function getFAQCats2Array() {

    global $dbh;

    try {
      $q = '
            SELECT
                `id`        AS ci,
                `name`      AS n
            FROM
                `faqcat`;
      ';

      $s = $dbh->query($q);

      // initialise an array for the results
      $A = array();

      while ($r = $s->fetch(PDO::FETCH_ASSOC)) {
          $A[] = $r;
      }

      $s = null;
      return $A;
    }

    catch(PDOException $e) {
      echo  "Something went wrong fetching the list of FAQ categories from the database.\n";
      file_put_contents(
          $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
          "\n\n\n\n".$e->__toString(), FILE_APPEND);
    }
  }

  public function getFAQ($i, $f) {

      global $dbh;

       try {
        $q = '
            SELECT
                '.$f.'
            FROM
                faq
            WHERE
                id = ?
        ';

        $s = $dbh->prepare($q);
        $s->execute(array($i));
        //$s->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $r = $s->fetch();

        return $r[$f];

      }

      catch(PDOException $e) {
        echo  "Something went wrong fetching the FAQ answer from the database.\n";
        file_put_contents(
            $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
            "\n\n\n\n".$e->__toString(), FILE_APPEND);

      }

  }

}

(There were other functions in the class using the same connection string in $dbh, but I've removed them for simplicities sake)

4

3 回答 3

1

你可以简单地敲击global $dbh!全局变量通常是一个非常糟糕的主意,并且会使您的代码更难维护。

在这种情况下,我建议使用类属性(有点全局,但仅在此类中):

class DB
{
    protected $dbh;

    public function __construct()
    {
        $this->dbh = new PDO();
    }

    public function query()
    {
        return $this->dbh->query();
    }
}

我在这里剥离并简化了很多代码,但这应该让您了解类属性的一般工作方式。您还可以在 PHP.net 手册上阅读很多关于此的内容。

于 2013-07-26T07:22:08.877 回答
0

给你。。

class DB {

  protected $dbh;

  public function __construct() {   

    try {
      $this->dbh  = new PDO('mysql:host=localhost;dbname=main_db', 'my_user', 'my_pass');
      $this->dbh  ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    catch(PDOException $e) {
      echo $e->getMessage();
    }
  }

  public function getFAQCats2Array() {  

    try {
      $q = '
            SELECT
                `id`        AS ci,
                `name`      AS n
            FROM
                `faqcat`;
      ';

      $s = $this->dbh->query($q);

      // initialise an array for the results
      $A = array();

      while ($r = $s->fetch(PDO::FETCH_ASSOC)) {
          $A[] = $r;
      }

      $s = null;
      return $A;
    }

    catch(PDOException $e) {
      echo  "Something went wrong fetching the list of FAQ categories from the database.\n";
      file_put_contents(
          $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
          "\n\n\n\n".$e->__toString(), FILE_APPEND);
    }
  }
}
于 2013-07-26T07:20:34.723 回答
0

不要使用global $dbh.

例如,只需向您的 DB 类添加一个属性,protected $db然后将您的 PDO 实例放入$this->db其中,因为您$db只能在对象内部使用 var。这是使用某种“数据库模型”的基本方法,您可以在其中通过网络找到大量教程 :)

例如 :

public __construct($db_type = 'mysql', $host = 'my_server', $database = 'db_name', $user = 'my_user', $pwd = 'password') {
    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;

    $dsn = $db_type.':host=' . $host . ';dbname=' . $database . '';

    try {
        $this->db = new PDO($dsn, $user, $pwd, $pdo_options);
    } catch (Exception $e) {
        'Unable to connect to database';
    }
}

然后在全局范围内创建对象的实例,脚本在其中使用它:

$db_manager = new DB('mysql','localhost','my_db','root','password');

然后您$db_manager将能够使用您DB班级的公共方法

于 2013-07-26T07:16:16.403 回答