简体   繁体   中英

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. 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:

$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?

The problem was how the test1() function was written. 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. 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).

The result is a multidimensional array of stdClass Objects:

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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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