我一直在尝试从db表输出数据,但我似乎无法做到,无论我做什么都不会出现。我试过使用foreach但没有骰子。这段代码取自phpacademy教程,我试图通过添加一些功能来修改它,比如能够使用pdo从数据库中收集所有数据
$bgItems = DB::getInstance()->getAll('background_image');
echo '<pre>', var_dump($bgItems), '</pre>';
foreach($bgItems as $bgItem) {
echo $bgItem;
}
使用我想要实现的方法,这就是DB类的样子:
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
else {
$sql = "{$action} FROM {$table}";
if(!$this->query($sql)->error()) {
return $this;
}
}
return false;
}
public function getAll($table) {
return $this->action('SELECT *', $table);
}
这是我在尝试查看使用var_dump检索的数据时得到的输出,这显然看起来像一个复杂的数组。
object(DB)#3 (5) {
["_pdo":"DB":private]=>
object(PDO)#4 (0) {
}
["_query":"DB":private]=>
object(PDOStatement)#8 (1) {
["queryString"]=>
string(30) "SELECT * FROM background_image"
}
["_error":"DB":private]=>
bool(false)
["_results":"DB":private]=>
array(3) {
[0]=>
object(stdClass)#7 (2) {
["id"]=>
string(1) "1"
["name"]=>
string(28) "4ee269991861331957002e21.jpg"
}
[1]=>
object(stdClass)#9 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(36) "22769-interesting-cat-meme-rv31.jpeg"
}
[2]=>
object(stdClass)#10 (2) {
["id"]=>
string(1) "3"
["name"]=>
string(50) "10645322_300758350130075_5393354656605964412_n.jpg"
}
}
["_count":"DB":private]=>
int(3)
}
已更新
这是直接从DB类
返回protected _results变量的结果时的结果 array(3) {
[0]=>
object(stdClass)#7 (2) {
["id"]=>
string(1) "1"
["name"]=>
string(28) "4ee269991861331957002e21.jpg"
}
[1]=>
object(stdClass)#9 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(36) "22769-interesting-cat-meme-rv31.jpeg"
}
[2]=>
object(stdClass)#10 (2) {
["id"]=>
string(1) "3"
["name"]=>
string(50) "10645322_300758350130075_5393354656605964412_n.jpg"
}
}
答案 0 :(得分:0)
你需要返回结果而不是类本身,你可以使用类,但是你需要实现迭代器。
public function getAll($table) {
if( $this->action('SELECT *', $table) ) return $this->_results;
return false;
}
答案 1 :(得分:0)
我刚将对象转换为数组,以便使用此
进行操作class Convert {
public function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map([__CLASS__, __METHOD__], $d);
} else {
// Return array
return $d;
}
}
}