将mysql转换为PDO的问题

时间:2014-06-16 21:13:49

标签: php mysql pdo

所以我在将我的应用程序从旧的mysql语法转换为PDO时遇到了一些麻烦。

这是我到目前为止所尝试的内容,旧的mysql行被注释掉了。

db_connect.php
<?php

class DB_Connect {

    // constructor
    function __construct() {

    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        require_once 'config.php';
        // connecting to mysql
        try {
        $pdo = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
        }
        catch (PDOException $e) {
            $output = 'Unable to connect to database server.' .
            $e->getMessage();
            exit();
        }

       // $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        //mysql_select_db(DB_DATABASE);

        // return database handler
        return $pdo;
    }

    // Closing database connection
    public function close() {
        $pdo = null;
    }

} 
?>

这是我的db_functions类,其中发生了所有CRUD操作,其中我使用db_connect类返回我可以使用的连接

db_functions.php
<?php

class DB_Functions {

private $db;

// constructor
function __construct() {
    include_once './db_connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

public function storeUser($name, $email, $gcm_regid) {
    //insert user into database
    try {
        $sql = "INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())";
        $result = $db->query($sql);
        if ($result) {
            // get user details
            $id = $db->lastInsertId(); //last inserted id
            $sql = "SELECT * FROM gcm_users WHERE id = $id";
            $result = $db->query($sql);
            $no_of_rows = $result->fetchColumn();
            // return user details
            if ($no_of_rows > 0) {
                     return $result->fetch(PDO::FETCH_ASSOC);
            } else {
                    return false;
            }
    } else {
        return false;
    }
    }
    catch (PDOException $e) {
        $error = 'Error storing user: ' . $e->getMessage();
    }
}


/*    // insert user into database
    $result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
    // check for successful store
    if ($result) {
        // get user details
        $id = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
        // return user details
        if (mysql_num_rows($result) > 0) {
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    } else {
        return false;
    }
}
   */

//Get user by email or password
public function getUserByEmail($email) {
    try {
    $sql = "SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1";
    $result = $db->query($sql);
    return $result;
    }
    catch (PDOException $e) {
        $error = 'Error fetching user by email: ' . $e->getMessage();
    }
  //  $result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");

}

//Returns all users
public function getAllUsers() {
    try {
    $sql = "select * FROM gcm_users";
    //$result = mysql_query("select * FROM gcm_users");
    $result = $db->query($sql);
    return $result;
    }
    catch (PDOException $e) {
        $error = 'Error getting all users: ' . $e->getMessage();
    }
}



//Check if user exists
public function isUserExisted($email) {
    try {
        $sql = "SELECT email from gcm_users WHERE email = '$email'";
        $result = $db->query($sql);
        $no_of_rows = $result->fetchColumn();


    //$result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");
    //$no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        // user existed
        return true;
    } else {
        // user not existed
        return false;
    }
    }
    catch (PDOException $e) {
        $error = 'Error fetching user by email: ' . $e->getMessage();
    }
}

我仅使用db_connect类测试了代码,它似乎正好连接到数据库,但是当我开始更新db_functions类时,我收到了错误

Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 84

Fatal error: Call to a member function query() on a non-object in      C:\xampp\htdocs\gcm\db_functions.php on line 84

这是第84行

   public function getAllUsers() {
        try {
        $sql = "select * FROM gcm_users";
        //$result = mysql_query("select * FROM gcm_users");
        $result = $db->query($sql); //Line 84
        return $result;

它似乎与它有关,它没有将$ db视为表示从db_connect中的connect()方法返回的PDO连接对象。有什么方法可以解决这个问题吗?

编辑:

尝试一起删除db_connect.php并在db_functions.php中创建PDO连接

class DB_Functions {

    private $db;

    // constructor
    function __construct() {
        require_once 'config.php';
        // connecting to mysql
        try {
        $this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
        }
        catch (PDOException $e) {
            $output = 'Unable to connect to database server.' .
            $e->getMessage();
            exit();
        }
    }

    // destructor
    function __destruct() {

    }

//Returns all users
public function getAllUsers() {
    try {
    $sql = "select * FROM gcm_users";
    //$result = mysql_query("select * FROM gcm_users");
    $result = $this->$db->query($sql);
    return $result;
    }
    catch (PDOException $e) {
        $error = 'Error getting all users: ' . $e->getMessage();
    }
}

现在收到错误:

Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12

Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12

这是第12行:

$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);

我尝试使用此处列出的第一个答案中的大纲:How do I create a connection class with dependency injection and interfaces?

1 个答案:

答案 0 :(得分:1)

您没有将$this->db->connect()的结果存储到以后可以使用的任何变量中,因此您的类从一开始就没有引用数据库连接。

您还没有在$this->db处正确引用(应该是)数据库连接,而只是调用$db->*

你有一种使用单例的不合理的方法,但我建议只使用依赖注入。所以也许放弃使用DB_Connect类并简单地将一个PDO对象直接注入到你的DB_Function类中(它应该可以称为user类)。

class DB_Functions {

    // note I changed this to protected in case you actually decide
    // to change class name to something meaningful like "user"
    // and want to ever subclass it        
    protected $db;

    // constructor
    function __construct(PDO $pdo) {
        $this->db = $pdo;
    }

    // rest of your class
    // make sure you replace $db->* references with $this->db->*
}

这做了一些事情。如果没有传入正确实例化的PDO对象,它实际上将失败DB_Functions对象的实例化。你是&#34;注入&#34;你的依赖(有一个有效的PDO对象)到这个类。没有它,对象实例化就会失败,这可能是一种理想的行为,因为如果没有有效的数据库连接,那么实例化该对象是没有用的。

这也有助于解除用户与用户的联系。来自DB实例化逻辑的逻辑。毕竟,为什么这个用户类需要知道如何实例化PDO对象。代码的其他部分应该处理设置PDO连接并将其传入,以便在某些时候,当您想要停止使用DB_Connect以支持某些其他PDO提供程序时,您将不需要更改此类和其他类似的类来引用一些新的PDO提供程序类。