我一直在试图从数据库表输出数据,但我似乎无法做到,无论我做什么,它都不会显示出来。我尝试使用foreach但没有骰子。此代码从phpacademy教程拍摄,我试图通过添加一些功能,如能够使用PDOPDO,输出表中的所有数据
$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)
}
修订
这是结果时,直接返回从保护_results变量从DB类所采取的结果
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"
}
}
我会建议你使用'notORM'库转换的对象到一个数组,以操纵它,它适用于PDO和很好的API – Saqueib 2014-09-30 10:45:38