我是OOP和PDO的新手。提前感谢任何帮助!
我在将 SQL 查询结果循环到页面时遇到问题。
这是我的笔记.php
$note->tulosta_notet('notes');
在课堂上 注意我有方法
public function tulosta_notet($table) {
$sql ="SELECT * FROM " . $table . "";
$result = $this->_db->query($sql);
echo "<br />";
print_r($result);
foreach ($result as $row) {
print $row["id"] . "-" . $row["note_text"] ."<br/>";
}
}
我通过print_r($result);
得到了正确的结果
所以查询是正确的,我只是无法让行正确打印到页面。
这是 print_r($result) 的输出;
DB Object ( [_pdo:DB:private] => PDO Object ( )
[_query:DB:private] => PDOStatement Object ( [queryString] => SELECT * FROM notes )
[_error:DB:private] => [_results:DB:private] => Array (
[0] => stdClass Object (
[id] => 1
[created] => 2015-03-08 13:50:43 [edited] => 2015-03-08 14:50:43
[note_text] => hei hei moi moi hei hei hei [
user_id] => 1 )
[1] => stdClass Object (
[id] => 2
[created] => 2015-03-08 14:23:55
[edited] => 2015-03-08 15:23:55
[note_text] => text text text text text text text text text text text text text text text text text text
[user_id] => 1 )
) [_count:DB:private] => 2 )
我做错了什么?
我宁愿在 notes.inc.php 中进行循环,我应该从 tulosta_notet() 返回什么才能让它工作?谢谢
-E
这是var_dump($this->_db);出口;
object(DB)#3 (5) {
["_pdo":"DB":private]=> object(PDO)#4 (0) { }
["_query":"DB":private]=> object(PDOStatement)#9 (1) {
["queryString"]=> string(28) "SELECT * FROM notes"
}
["_error":"DB":private]=> bool(false)
["_results":"DB":private]=> array(2) {
[0]=> object(stdClass)#5 (5) {
["id"]=> string(1) "1"
["created"]=> string(19) "2015-03-08 13:50:43"
["edited"]=> string(19) "2015-03-08 14:50:43"
["note_text"]=> string(27) "hei hei moi moi hei hei hei"
["user_id"]=> string(1) "1"
}
[1]=> object(stdClass)#10 (5) {
["id"]=> string(1) "2"
["created"]=> string(19) "2015-03-08 14:23:55"
["edited"]=> string(19) "2015-03-08 15:23:55"
["note_text"]=> string(90) "text text text text text text text text text text text text text text text text text text " ["user_id"]=> string(1) "1"
}
} ["_count":"DB":private]=> int(2) }
类 DB 中的 query()
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) {
// echo $param;
$this->_query->bindValue($x, $param);
$x++;
// echo $x."<br>";
}
}
if($this->_query->execute()) {
echo "Success";
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
在你的"query"方法中,你使用一个流畅的接口(返回$this
返回当前对象)。因此,当您print_r()
时,将打印一个对象。
修改查询方法或使用获取函数,如下所示:
public function tulosta_notet($table) {
$sql = "SELECT * FROM " . $table;
$stmt = $this->_db->prepare($sql);
$res = $stmt->execute();
for ($i = 0; $i < count($res); $i++) {
print $res[$i]["id"] . "-" . $res[$i]["note_text"] ."<br/>";
}
}