使用PDO对象进行Select查询

时间:2014-11-21 08:33:52

标签: php mysql pdo

我是PDO的初学者。我正在学习PDO的教程。我想使用一个简单的select语句来获取用户的id。

但是当我运行index.php时,它不显示任何echo!我哪里错了?

我有四个文件:

config =>设置用户名和密码......

DB_Connect:

class DB_Connect {

    // constructor
    function __construct() {

    }

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

    // Connecting to database
    public function connect() {
        require_once 'include/config.php';
        try {
            $hostname = DB_HOST ;
            $dbname   = DB_DATABASE;
            $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", DB_USER, DB_PASSWORD);
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }

        return $dbh;
    }



}

DB_Functions:

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }


    function getUsers(){

        $sql = "SELECT * FROM users";
        foreach ($this->$db->query($sql) as $row)
        {
            echo $row->id;
        }

        /*** close the database connection ***/
      //  $db = null;

    }
}

的index.php

<?php

    require_once 'include/DB_Functions.php';
    $qr = new DB_Functions();
    $qr->getUsers();



?>

1 个答案:

答案 0 :(得分:1)

db_connect

class DB_Connect {
    public $dbh;
    // constructor
    function __construct() {

    }

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

    // Connecting to database
    public function connect() {
        require_once 'include/config.php';
        try {
            $hostname = DB_HOST ;
            $dbname   = DB_DATABASE;
            $this->dbh = new PDO("mysql:host=$hostname;dbname=$dbname", DB_USER, DB_PASSWORD);
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
}

db_functions

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }


    function getUsers(){

        $sql = "SELECT * FROM users";
        foreach ($this->db->dbh->query($sql) as $row)
        {
            echo $row->id;
        }

        /*** close the database connection ***/
      //  $db = null;

    }
}

您没有数据库连接,因为您现在正在将PDO连接分配给变量。因此,您的其他脚本无法访问您的连接。至少,这就是我现在所想的。