使用PDO连接到MySQL时出现问题 [英] Problems connecting to MySQL using PDO

查看:107
本文介绍了使用PDO连接到MySQL时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将我的应用程序从使用已贬值的mysql语法转换为PDO以连接到数据库并执行查询,到目前为止,这一直很痛苦.

I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.

现在,我有一个类db_functions.php,我在其中尝试创建与数据库的PDO连接,并在其中执行所有CRUD操作.

Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.

以下是代码示例:

db_functions.php
<?php

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() {

    }

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();
    }
}

使用该代码,出现以下错误:

With that code, i'm getting the following error:

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);

如何解决此问题,以使我拥有与数据库的PDO连接的正确实例,可用于在db_functions中的其他方法(例如getAllUsers()

How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()

我使用了在如何创建具有依赖项注入和接口的连接类?无济于事.

I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.

推荐答案

TYPO

//$this->$db = 
$this->db = 

在这里

//$this->$db->query($sql);
$this->db->query($sql);

并且我也将使用127.0.0.1而不是localhost来提高性能,否则建立连接将花费很长时间...仅几秒钟即可建立连接...

and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

这篇关于使用PDO连接到MySQL时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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