【问题标题】:Using MYSQLi prepared statements in a PHP class [duplicate]在 PHP 类中使用 MYSQLi 准备好的语句 [重复]
【发布时间】:2012-12-13 08:59:41
【问题描述】:

可能重复:
How to access mysqli connection in another class on another page?

我有一个用于连接 MYSQLi 数据库的 PHP 类,我想在另一个类中使用这个类来创建准备好的语句并显示来自数据库的一些信息。

这可能吗?

<?php 

    class database {

        public $host = "localhost";
        public $user = "root";
        public $password = "root";
        public $name = "store";


        public function connect() {

            $connect = new mysqli($this->host, $this->user, $this->password, $this->name);

            if($connect->connect_errno > 0){
                die('Unable to connect to database [' . $connect->connect_error . ']');
            }

        }

    }


    class products {

    // In here I want to use a MYSQLi prepared statment to show some information
    // from the database details in the class above

    }



    $database = new database();
    $database->connect(); 

    ?>

提前致谢!

【问题讨论】:

  • 是的,这是可能的。实例化和使用。我们在这个主题上有一些重复。

标签: php mysqli prepared-statement


【解决方案1】:

您必须在引导程序中连接某个地方,而不是在其他类中连接,将类实例放入变量中。然后您就可以将此变量传递给构造函数参数或简单使用

global $db;
$this->db = $db;

在构造函数中

顺便说一句,我认为单独的 connect() 方法没有用。为什么不在构造函数中直接连接?
另外让我建议您不要使用die(),而是使用trigger_error()(或例外)。

【讨论】:

  • 所以一旦将类定义为 var,我可以在另一个类中这样称呼它:$db
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
相关资源
最近更新 更多