如何在 PHP 中通过 PDO 循环遍历 MySQL 查询?

How do I loop through a MySQL query via PDO in PHP?

提问人:Andrew G. Johnson 提问时间:10/2/2008 最后编辑:Alive to die - AnantAndrew G. Johnson 更新时间:5/12/2021 访问量:60134

问:

我正在慢慢地将我所有的函数从一个函数转移到另一个函数,我已经撞上了我的第一堵砖墙。我不知道如何使用参数遍历结果。我对以下方面感到满意:LAMP websitesmysql_PDO

foreach ($database->query("SELECT * FROM widgets") as $results)
{
   echo $results["widget_name"];
}

但是,如果我想做这样的事情:

foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
   echo $results["widget_name"];
}

显然,“其他东西”将是动态的。

php mysql pdo

评论


答:

8赞 Darryl Hein 10/2/2008 #1

根据PHP文档,您应该能够执行以下操作:

$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $row) {
   echo $row["widget_name"];
}

评论

3赞 DGM 10/2/2008
这并不能逃避可能是动态的“其他东西”。Shabbyrobe 所示的准备好的查询就是答案。
6赞 Evan Teran 10/24/2008
@DGB,达里尔的“别的东西”来自原始问题的例子。该问题与动态组合查询无关,它与迭代查询结果有关。他回答正确。虽然我同意 Shabbyrobe 给出了更好的答案。
4赞 Ry- 6/25/2013
“显然,'别的东西'将是动态的。
75赞 Shabbyrobe 10/2/2008 #2

下面是一个使用 PDO 连接到数据库的示例,告诉它抛出 Exceptions 而不是 php 错误(这将有助于您的调试),以及使用参数化语句而不是自己将动态值替换到查询中(强烈推荐):

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");

// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare the statement. the placeholders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");

// bind the parameters
$stmt->bindValue(":productTypeId", 6);
$stmt->bindValue(":brand", "Slurm");

// initialise an array for the results
$products = array();
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $products[] = $row;
}
3赞 John K 6/14/2013 #3

如果您喜欢 foreach 语法,可以使用以下类:

// Wrap a PDOStatement to iterate through all result rows. Uses a 
// local cache to allow rewinding.
class PDOStatementIterator implements Iterator
{
    public
        $stmt,
        $cache,
        $next;

    public function __construct($stmt)
    {
        $this->cache = array();
        $this->stmt = $stmt;
    }

    public function rewind()
    {
        reset($this->cache);
        $this->next();
    }

    public function valid()
    {
        return (FALSE !== $this->next);
    }

    public function current()
    {
        return $this->next[1];
    }

    public function key()
    {
        return $this->next[0];
    }

    public function next()
    {
        // Try to get the next element in our data cache.
        $this->next = each($this->cache);

        // Past the end of the data cache
        if (FALSE === $this->next)
        {
            // Fetch the next row of data
            $row = $this->stmt->fetch(PDO::FETCH_ASSOC);

            // Fetch successful
            if ($row)
            {
                // Add row to data cache
                $this->cache[] = $row;
            }

            $this->next = each($this->cache);
        }
    }

}

然后使用它:

foreach(new PDOStatementIterator($stmt) as $col => $val)
{
    ...
}