在另一个文件中访问PHP PDO对象 [英] Access the PHP PDO object in another file

查看:54
本文介绍了在另一个文件中访问PHP PDO对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在generic.php中有一个称为generic的类.我有一个signup.php文件,它必须执行SQL查询.但是,我无法访问在$ db中存储的generic.php中创建的PDO对象.

I have a class called generic in generic.php. I have a signup.php file which has to perform SQL queries. However, I can't access the PDO object created in generic.php that's stored in the variable $db.

通用类如下:

class Generic {
    public $db;

    public function connect_database() {
        define('USER', 'user');
        define('PASSWORD', 'password');

        // Database connection
        try {
            $connection_string = 'mysql:host=localhost;dbname=mydb;charset=utf8';
            $connection_array = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );

            $db = new PDO($connection_string, USER, PASSWORD, $connection_array);
            echo 'Database connection established';
        }
        catch(PDOException $e) {
            $db = null;
        }
    }   
}

我尝试访问$ db变量(存储PDO对象的变量),但是出现错误消息Call to a member function prepare() on a non-object in....这是我的signup.php文件当前的样子:

I try to access the $db variable (in which the PDO object is stored), but I get an error saying Call to a member function prepare() on a non-object in.... This is how my signup.php file currently looks like:

// Require needed classes
require_once('generic.php');

// Create needed objects
$generic = new Generic();

$datetime = date("Y-m-d H:i:s");

try {
    $sql = "INSERT INTO user(
        email, 
        name, 
        username, 
        password
    ) 
    VALUES(
        :email, 
        :name, 
        :username, 
        :password 
    )";

    $stmt = $db->prepare($sql);

    $stmt->bindParam(':email', 'myemail@email.com', PDO::PARAM_STR);       
    $stmt->bindParam(':name', 'John Doe', PDO::PARAM_STR); 
    $stmt->bindParam(':username', 'johndow', PDO::PARAM_STR);
    // use PARAM_STR although a number  
    $stmt->bindParam(':password', 'test123', PDO::PARAM_STR);   

    $stmt->execute();
} 
catch(PDOException $e) {
    echo $e;
}

我找不到在signup.php文件中通过数据库连接获取$ db变量的方法,因此可以执行查询.我已经尝试过$db = $generic->db,但这没什么区别.

I can't find a way to get the $db variable with the database connection in my signup.php file, so I can execute the query. I've tried $db = $generic->db, but that doesn't make any difference.

我是OOP PHP的新手,正在尝试一些东西.我希望这个问题能解释我的问题.

I'm new to OOP PHP and trying some stuff out. I hope this questions explains my problem.

推荐答案

首先,您没有调用"connect_database"函数,因此$ db变量为null. 顺便说一句,我建议使用一个描述性名称来命名该类,例如"DBHandler".

First, you didn't call the "connect_database" function, so your $db variable is null. By the way, I recommend naming the class with a descriptive name, for example "DBHandler".

您将"connect_database"函数更改为private,只需在构造函数中调用它即可.另外,将$ db设为私有,并设置一个getter函数以获取更具可读性的代码.

You change the "connect_database" function to private, and simply call it in the constructor. Also, make $db private and set a getter function for more readable code.

class DBHandler {
    private $db;

    function __construct() {
        $this->connect_database();
    }

    public function getInstance() {
        return $this->db;
    }

    private function connect_database() {
        define('USER', 'user');
        define('PASSWORD', 'password');

        // Database connection
        try {
            $connection_string = 'mysql:host=localhost;dbname=mydb;charset=utf8';
            $connection_array = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );

            $this->db = new PDO($connection_string, USER, PASSWORD, $connection_array);
            echo 'Database connection established';
        }
        catch(PDOException $e) {
            $this->db = null;
        }
    }   
}

现在您可以像这样使用代码了(注意,我已经更改了文件名和类名):

Now you can use your code like this (notice I've changed the file name and class name):

// Require needed classes
require_once('dbhandler.php');

// Create needed objects
$dbh = new DBHandler();

// Check if database connection established successfully
if ($dbh->getInstance() === null) {
    die("No database connection");
}

$datetime = date("Y-m-d H:i:s");

try {
    $sql = "INSERT INTO user(
        email, 
        name, 
        username, 
        password
    ) 
    VALUES(
        :email, 
        :name, 
        :username, 
        :password 
    )";

    $stmt = $dbh->getInstance()->prepare($sql);

    $stmt->bindParam(':email', 'myemail@email.com', PDO::PARAM_STR);       
    $stmt->bindParam(':name', 'John Doe', PDO::PARAM_STR); 
    $stmt->bindParam(':username', 'johndow', PDO::PARAM_STR);
    // use PARAM_STR although a number  
    $stmt->bindParam(':password', 'test123', PDO::PARAM_STR);   

    $stmt->execute();
} 
catch(PDOException $e) {
    echo $e;
}

更新:

此外,除非您的值将在bindParam和execute调用之间更改,否则您不需要使用bindParam.

More so, You don't need to user bindParam unless your values will change between the bindParam and the execute call.

您可以简单地将数组中的值传递给execute:

You can simply pass the values in an array to the execute:

$stmt->execute(array(':email' => 'email address', ':name' => 'Name', ':username' => 'User name', ':password' => 'Your password'));

这篇关于在另一个文件中访问PHP PDO对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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