简体   繁体   English

如何使用带有pdo的fetch(PDO :: FETCH_ASSOC)获取多个行?

[英]How do I fetch mulitiple rows using fetch(PDO::FETCH_ASSOC) with pdo?

testQuery() is the method I use to get all rows from table CATEGORIES testQuery()是我用来从表CATEGORIES获取所有行的方法

public function __construct()
 {
 self::$tdb = Database::getConnection();
 }



 #mock query to pull results from db
 public function testQuery()
  {
       $queryAA = "SELECT cat_name, cat_description, cat_id FROM CATEGORIES";
       $stmtAA = self::$tdb->prepare($queryAA);


       if ($stmtAA->execute() == true)
        {
             print("Execution was successful");
             return $stmtAA->fetch(PDO::FETCH_ASSOC);   
        }
       else
        {
            print("Warning statment did not successfully execute");
        }
     }

I normally use fetchAll() but I was told to use fetch as it doesn't take up as much memory. 我通常使用fetchAll()但我被告知使用fetch,因为它不会占用太多内存。 But I am having trouble retrieving more than one row using fetch() and the code below. 但是我在使用fetch()和下面的代码检索多行时遇到问题。

$test = new test();
$results = $test->testQuery();


foreach ($results as $row)
 {
 print_r($row);
 }

It only fetches 1 row. 它只取1行。 So how do I retrieve and print multiple rows? 那么如何检索和打印多行? Using iteration was mentioned before but I'm not sure to implement it. 之前提到过使用迭代,但我不确定是否实现它。 Any help would greatly be appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

Fetch does indeed pull the data from the database one at a time, but you need to iterate through the rows until you have all the data. Fetch确实一次从数据库中提取数据,但是您需要遍历行,直到获得所有数据。

You might want to pop this into a loop to get all the data: 您可能希望将其弹出到循环中以获取所有数据:

$stmtAA->fetch(PDO::FETCH_ASSOC);

Something like this should do the trick: 像这样的东西应该做的伎俩:

while($row=$this->prepared->fetch(PDO::FETCH_ASSOC))
{
    $this->ID=$row['id'];
    $something=$row['something'];
}

Depending on if you are populating variables or have the code within an object. 取决于您是填充变量还是在对象中包含代码。

You could simply return the statement object. 您只需返回语句对象即可。
Or if you want to encapsulate it (so that it can only be used to fetch the data) use the SPL's IteratorIterator 或者,如果要封装它(以便它只能用于获取数据),请使用SPL的IteratorIterator

return new IteratorIterator($stmtAA);

then you can use 然后你可以使用

foreach( testQuery() as $row) { ... }

in your script. 在你的脚本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM