[英]Fetched SQL statement (PDO) returns an object at the 0 index o the array
我從使用PDO所做的sql語句中獲取了一些結果,每當我將其放在數組上時,它都是這樣的:
initialize Object ( [conn:protected] => PDO Object ( ) [container:protected] => Array ( [0] => 1,Philippine Tax,2 ) )
每當我遍歷返回的數組時,都會出現一個錯誤,即它無法顯示對象。 這是我的代碼:
<?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);
嘗試這樣的事情。 得到自己的原因是因為您試圖獲取有關對象的信息,本質上是對象的映射。 如果您試圖返回一個數組,則需要通過一種方法來返回它,而不是通過__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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.