获取的SQL语句(PDO)返回数组的0索引处的对象

时间:2014-10-14 03:18:58

标签: php mysql arrays pdo

我从使用PDO的sql语句中获取一些结果,每当我将它放在数组上时,它就像这样:

initialize Object ( [conn:protected] => PDO Object ( ) [container:protected] => Array ( [0] => 1,Philippine Tax,2 ) )

每当我对返回的数组进行FOREACH时,它都会给出一个错误,它无法显示一个对象。这是我的代码:

<?php
class initialize{
    protected $conn = NULL;
    protected $container = array();

    function __construct(){
        $this->conn = $this->connect();

        $ed_fetch = $this->conn->prepare("SELECT * FROM table");
        if ($ed_fetch->execute()){
            while ($row = $ed_fetch->fetch( )){
                array_push($this->container, $row[0] . ',' . $row[1] . ',' . $row[2]);
            }
        }

        return $this->container;
    }

    protected function connect(){
        $this->conn = new PDO("mysql:host=localhost;dbname=db", 'root');
        if (!$this->conn){
            echo "Error, could not connect to the database, contact the administrator";
        }
        else{
            return $this->conn;
        }
    }
}
?>

我的展示:

$new = new initialize();
print_r($new);

1 个答案:

答案 0 :(得分:0)

尝试这样的事情。你得到自己的原因是因为你试图获得关于对象的信息,实质上是对象的映射。如果你试图返回一个数组,你需要通过一个方法返回它,而不是通过__construct作为返回。

class Initialize
    {
        protected   $conn       =   NULL;
        protected   $container  =   array();
        protected   $creds;
        protected   $username;
        protected   $password;

        public  function __construct($creds = "mysql:host=localhost;dbname=db", $username = 'root', $password = '')
            {
                $this->creds    =   $creds;
                $this->username =   $username;
                $this->password =   $password;
                $this->conn     =   $this->connect();
            }

        public function Fetch($sql)
            {
                $ed_fetch   =   $this->conn->prepare($sql);
                $ed_fetch->execute();

                if ($ed_fetch->rowCount() > 0){
                        while ($row = $ed_fetch->fetch()){
                                $this->container[]  =   $row[0].','.$row[1].','.$row[2];
                            }
                    }

                return $this->container;
            }

        protected function connect()
            {
                try {
                        $this->conn = new PDO($this->creds,$this->username,$this->password);
                    } catch (PDOException $e) {
                        echo "Error, could not connect to the database, contact the administrator<br/>";  //. $e->getMessage() . 
                        die();
                    }
            }
    }

    $query  =   new Initialize();
    $array  =   $query->Fetch("SELECT * FROM table");

    print_r($array);