PHP类数据库交互(使用PDO)

发布于 2024-09-08 17:55:32 字数 1927 浏览 3 评论 0原文

大家好,我对面向对象的 PHP 完全陌生——我读过一些教程,但我找不到任何真正涉及使用 PHP 类的数据库的内容。

我正在尝试做一些简单的事情——一个快速的新闻发布课程。您从数据库等获取帖子。但是,每当我尝试与数据库交互时,我都会收到错误。

我读到 PDO 是 OO PHP 的最佳选择;为此,我开发了一个数据库类,详见这篇文章: Use of PDO in然后

class Database
{
    public $db;   // handle of the db connexion
    private static $dsn  = "mysql:host=localhost;dbname=test";
    private static $user = "admin";
    private static $pass = "root";
    private static $instance;

    public function __construct () 
    {
        $this->db = new PDO(self::$dsn,self::$user,self::$pass);
    }

    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            $object= __CLASS__;
            self::$instance=new $object;
        }
        return self::$instance;
    }

    // others global functions
}

,我尝试在我的 PHP 类中使用它,以便检索新闻帖子上的数据:

<?php
require_once "database.php";

class news extends Database
{
    private $title;
    private $author;
    private $date;
    private $content;
    private $category;


    function __construct($id)
    {
        $db = Database::getInstance();
        $query = $this->db->prepare("SELECT title, author, date, content, category FROM news WHERE id = :id LIMIT 1");
        $query->bindParam(":id", $this->id, PDO::PARAM_INT);
        if ($query->execute())
        {
            $result = $query->fetch(PDO::FETCH_OBJ);

            $this->set_title($result->title);
            $this->set_author($result->author);
            $this->set_date($result->date);
            $this->set_content($result->content);
            $this->set_category($result->category);
        }
    }
<...>
?>

不过,每次我尝试运行此脚本时,都会收到以下错误:

致命错误:调用成员函数第 16 行 /news.class.php 中的非对象上的prepare()

有什么想法吗?

Hey guys, so I'm completely new to Object Oriented PHP -- I've read some tutorials, but I can't find anything that really goes into working with a database with PHP classes.

I'm trying to make something simple -- a quick news post class. You get the post from the database, etc. However, I'm getting an error whenever I try to interact with the database.

I read that PDO is the way to go with OO PHP; to that end, I've developed a database class, as detailed in this post: Use of PDO in classes

class Database
{
    public $db;   // handle of the db connexion
    private static $dsn  = "mysql:host=localhost;dbname=test";
    private static $user = "admin";
    private static $pass = "root";
    private static $instance;

    public function __construct () 
    {
        $this->db = new PDO(self::$dsn,self::$user,self::$pass);
    }

    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            $object= __CLASS__;
            self::$instance=new $object;
        }
        return self::$instance;
    }

    // others global functions
}

I then attempt to use it in my PHP class, in order to retrieve data on a news post:

<?php
require_once "database.php";

class news extends Database
{
    private $title;
    private $author;
    private $date;
    private $content;
    private $category;


    function __construct($id)
    {
        $db = Database::getInstance();
        $query = $this->db->prepare("SELECT title, author, date, content, category FROM news WHERE id = :id LIMIT 1");
        $query->bindParam(":id", $this->id, PDO::PARAM_INT);
        if ($query->execute())
        {
            $result = $query->fetch(PDO::FETCH_OBJ);

            $this->set_title($result->title);
            $this->set_author($result->author);
            $this->set_date($result->date);
            $this->set_content($result->content);
            $this->set_category($result->category);
        }
    }
<...>
?>

Every time I try to run this script though, I get the following error:

Fatal error: Call to a member function prepare() on a non-object in /news.class.php on line 16

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抱猫软卧 2024-09-15 17:55:32
$db = Database::getInstance();
$query = $this->db->prepare();

您必须两次使用 $db$this->db$db 是本地函数中的变量。 $this->db 是该类的实例变量。他们不一样。在这种情况下,$this->db 不存在,因此没有成员函数 prepare,如错误所述。

您尝试在父类的构造函数中创建 $this->db ,但由于您要覆盖子类中的构造函数,因此该代码不会运行。您需要调用 parent::__constructor 才能运行该代码。

$db = Database::getInstance();
$query = $this->db->prepare();

You'll have to use either $db or $this->db both times. $db is a variable in the local function. $this->db is an instance variable of the class. They're not the same. In this case, $this->db does not exist and as such has no member function prepare, as the error states.

You're trying to create $this->db in your parent's constructor, but since you're overriding the constructor in the child class, that code is not run. You would need to call parent::__constructor for that code to run.

a√萤火虫的光℡ 2024-09-15 17:55:32

你的设计有缺陷。新闻为什么要扩展数据库?数据库代表您的全局数据库连接。新闻表的一行不是数据库连接。所以它不应该继承它。你应该做的是遵循“优先组合而不是继承”的原则。

扩展单例并不是一个好主意。事实上,单例通常是一个坏主意,因为它们使您的代码变得单一。

您所做的基本上是对象关系映射。你应该看看一些现有的 PHP ORM,我建议 Doctrine

Your design is flawed. Why does news extend Database? Database represents your global database connection. One single row of the news table is not a database connection. So it should not inherit from it. What you should do is follow the "favor composition over inheritance" principle.

Extending a singleton is not a good idea. As a matter of fact, singletons are a bad idea in general, because they make your code monolithic.

What you are doing is basically object-relational mapping. You should take a look at some existing PHP ORMs, I suggest Doctrine.

初见你 2024-09-15 17:55:32

$db = 数据库::getInstance();
需要是:
$db = 新数据库();

这行 $query = $this->db->prepare();
需要是
$query = $db->prepare();

然后这个 $query->bindParam(":id", $this->id, PDO::PARAM_INT);
需要是
$query->bindParam(":id", $id, PDO::PARAM_INT);

我不确定为什么需要 Database 类中的 getInstance() 函数? new Database

()

将为您提供一个新实例。

$db = Database::getInstance();
need to be:
$db = new Database();

And this line $query = $this->db->prepare();
need to be
$query = $db->prepare();

Then this $query->bindParam(":id", $this->id, PDO::PARAM_INT);
need to be
$query->bindParam(":id", $id, PDO::PARAM_INT);

I'm not sure why you need the getInstance() function in the Database class? The

new Database()

will give you a new instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文