如何在 PHP 中通过 PDO 循环执行 MySQL 查询?

发布于 2024-07-07 06:36:33 字数 422 浏览 6 评论 0原文

我正在慢慢地将所有 LAMP 网站从 mysql_ 函数迁移到 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"];
}

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

I'm slowly moving all of my LAMP websites from mysql_ functions to PDO functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:

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

However if I want to do something like this:

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

Obviously the 'something else' will be dynamic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野生奥特曼 2024-07-14 06:36:33

下面是一个使用 PDO 连接到数据库的示例,告诉它抛出异常而不是 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;
}

Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):

// 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;
}
揽月 2024-07-14 06:36:33

根据 PHP 文档 说你应该能够做到下列:

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

According to the PHP documentation is says you should be able to to do the following:

$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $row) {
   echo $row["widget_name"];
}
岁月无声 2024-07-14 06:36:33

社区警告:由于 PDOStatement 已经可遍历,因此实际上不需要任何此类操作:您可以使用 foreach直接在PDOStatement上:


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

就这么简单

如果你喜欢 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)
{
    ...
}

Community warning: Since PDOStatement is already traversable, nothing of the sort is really needed: you can use foreach directly on PDOStatement:

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

as simple as that

If you like the foreach syntax, you can use the following class:

// 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);
        }
    }

}

Then to use it:

foreach(new PDOStatementIterator($stmt) as $col => $val)
{
    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文