简体   繁体   English

使用PDO时提取SELECT查询的结果

[英]extracting results of a SELECT query when using PDO

I am having difficulty figuring out how to extracting results of a SELECT query when using PDO in PHP. 我很难弄清楚如何在PHP中使用PDO时如何提取SELECT查询的结果。 Here is my database class: 这是我的数据库类:

class DB
{
    # ATTRIBUTES
    private static $_instance = null;   # stores instance of the db, if it's available
    private $_pdo,
            $_query,
            $_error = false,
            $_results,
            $_count = 0;

    # METHODS
    # connect to database           
    private function __construct()
    {
        try
        {
            $this->_pdo = new PDO('sqlsrv:Server=' . DB_HOST . ';Database=' . DB_NAME);
            // echo 'connected';    //enable this line to test db connection
        }
        catch(PDOException $e)
        {
            die($e->getMessage());
        }
    }

    # get database instance if it exists, otherwise create a database instance (this prevents repeatedly reconnecting to db)
    public static function getInstance()
    {
        if (!isset(self::$_instance)):
            self::$_instance = new DB();
        endif;
        return self::$_instance;
    }

    # generic query method
    public function query($sql, $parameters = array())
    {
        $this->_error = false;
        if ($this->_query = $this->_pdo->prepare($sql)):
            $x = 1;
            if (count($parameters)):
                foreach($parameters as $parameter):
                    $this->_query->bindValue($x, $parameter);
                $x++;
                endforeach;
            endif;
            if ($this->_query->execute()):
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            else:
                $this->_error = true;
            endif;
        endif;
        return $this;
    }

    # methods to return query results
    public function results()
    {
        return $this->_results;
    }

    public function firstresult()
    {
        return $this->results()[0];
    }

    # method to return errors
    public function error()
    {
        return $this->_error;
    }

    # method to return query row count
    public function count()
    {
        return $this->_count;
    }

}

Here is my test class: 这是我的测试课:

class XYZ
{
    # ATTRIBUTES
    private $_db,
            $_data;

    # METHODS
    public function __construct($test = null)
    {
        $this->_db = DB::getInstance();
    }

    public function test1()
    {
        $data = $this->_db->query('SELECT * FROM Users WHERE UserName LIKE ?;', ['Ad%']);
        $this->_data = $data;       
        return $this->_data;        
    }
}

And here is the usage of class XYZ to create an object plus a look at the results: 这是使用XYZ类创建对象以及查看结果的用法:

$x = new XYZ();
$y = $x->test1();
echo '<pre>' . print_r($y,1) . '</pre><br><br>';

The results appear to be the contents of the DB object: 结果似乎是数据库对象的内容:

DB Object
(
    [_pdo:DB:private] => PDO Object
        (
        )

    [_query:DB:private] => PDOStatement Object
        (
            [queryString] => SELECT * FROM Users WHERE UserName LIKE ?;
        )

    [_error:DB:private] => 
    [_results:DB:private] => Array
        (
            [0] => stdClass Object
                (
                    [UserID] => 1
                    [UserName] => Admin
                    [Password] => ²â€ÃœÂµÃ·Â©Ã¶Ã©rºó°TÈÃr^‡
                    [Email] => admin@website.com
                    [FirstName] => 
                    [LastName] => 
                    [BusinessName] => 
                    [Registered] => 2009-01-01 00:00:00.0000000
                    [UserType] => A
                    [Inserted] => 2014-03-06 19:40:23.6500000
                )

            [1] => stdClass Object
                (
                    [UserID] => 4
                    [UserName] => Adam1978
                    [Password] => ²â€ÃœÂµÃ·Â©Ã¶Ã©rºó°TÈÃr^‡
                    [Email] => adamjfinley@gmail.com
                    [FirstName] => Adam
                    [LastName] => Finley
                    [BusinessName] => 
                    [Registered] => 2014-02-14 16:19:22.0000000
                    [UserType] => R
                    [Inserted] => 2014-03-06 19:40:23.6500000
                )

        )

    [_count:DB:private] => 2
)

What needs to be done so the multidimensional array in the DB Object (see array key [_results:DB:private]) are accessible in class XYZ? 要做什么,才能在XYZ类中访问数据库对象中的多维数组(请参见数组键[_results:DB:private])?

The problem was how the test1() function was written. 问题在于如何编写test1()函数。 Here is, rewritten, with the code that worked: 这是使用有效的代码重写的:

public function test1()
    {

        $data = $this->_db->query('SELECT * FROM Users WHERE UserName LIKE ?;', ['Ad%']);   
        $this->_data = $data->results();
        return $this->_data;            
    }

$data in test1() appears to be the DB object. test1()中的$ data似乎是数据库对象。 In order to view the results of the SELECT query, the results() method of the DB class is accessible when using a DB object ($data in this case). 为了查看SELECT查询的结果,在使用DB对象(在这种情况下为$ data)时,可以访问DB类的results()方法。

The result is a multidimensional array of stdClass Objects: 结果是stdClass对象的多维数组:

Array
(
    [0] => stdClass Object
        (
            [UserID] => 1
            [UserName] => Admin
            [Password] => ²â€ÃœÂµÃ·Â©Ã¶Ã©rºó°TÈÃr^‡
            [Email] => admin@website.com
            [FirstName] => 
            [LastName] => 
            [BusinessName] => 
            [Registered] => 2009-01-01 00:00:00.0000000
            [UserType] => A
            [Inserted] => 2014-03-06 19:40:23.6500000
        )

    [1] => stdClass Object
        (
            [UserID] => 4
            [UserName] => Adam1978
            [Password] => ²â€ÃœÂµÃ·Â©Ã¶Ã©rºó°TÈÃr^‡
            [Email] => adamjfinley@gmail.com
            [FirstName] => Adam
            [LastName] => Finley
            [BusinessName] => 
            [Registered] => 2014-02-14 16:19:22.0000000
            [UserType] => R
            [Inserted] => 2014-03-06 19:40:23.6500000
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM