【问题标题】:PHP - create class for database accessPHP - 创建用于数据库访问的类
【发布时间】:2012-08-08 10:34:19
【问题描述】:

我想使用类创建数据访问。但出现问题。我的文档根目录是 public_html,所以我的 /resources 文件位于文档根目录之外

我在 /resources/dal/task.php 有一个数据访问层类

<?php
namespace resources\dal;

class task
{
public $result;
public function __construct()
{
    try {
        # MySQL with PDO_MYSQL
        $DBH = new PDO('mysql:host=localhost;dbname=test', 'root',     'abc123');
        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION,     PDO::NULL_EMPTY_STRING );
    }       
    catch(PDOException $e) {
        echo "I'm sorry. Please try again later.";  
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);  
    }
}

public function __destruct()
{
    $DBH = null;
}

public function select()
{
    $STH = $DBH->prepare("SELECT * FROM task");
    $STH->execute();
    $result = $STH->fetch(PDO::FETCH_ASSOC);
    $this->result = $result;
}
}
?>

这是我的主页(在 public_html 内)index.php

<?php
    spl_autoload_extensions(".php");
    spl_autoload_register(function ($class) {
    require $_SERVER["DOCUMENT_ROOT"] . '/../' . $class . '.php';
    });

use resources\dal as DAL;

$taskClass = new DAL\task();
$result = $taskClass->select();
    var_dump($result);
?>

我得到这个错误:

警告:要求(D:/DevelopmentWebSite/public_html/../resources\dal\PDO.php):无法打开流:第 14 行的 D:\DevelopmentWebSite\public_html\index.php 中没有这样的文件或目录

致命错误:require():在 D:\ DevelopmentWebSite\public_html\index.php 第 14 行

对不起,我对 PHP 很陌生。有人知道怎么了?

【问题讨论】:

  • 我对 Windows 上的 PHP 不是很熟悉,但您是否尝试将“/”更改为“\”?
  • 我猜你没有启用 PDO 扩展。如果你这样做了,它不会要求你的自动加载器加载 PDO 类...

标签: php mysql class pdo


【解决方案1】:

您正在使用局部变量 DBH。这意味着它在构造函数结束时丢失。

您可以创建成员变量: protected $DBH

在构造函数中:$this-&gt;DBH = new PDO(...

使用:$this-&gt;DBH-&gt;prepare(...

【讨论】:

  • 就是这样。我刚刚又学会了从头开始。我回头看这个问题,这是一个愚蠢的问题。 “$this”非常重要。谢谢user1591984
猜你喜欢
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多