如何通过 PDO 安全地执行包含 PHP 变量的 MySQL 查询?

问题描述 投票:0回答:3

我正在慢慢地将所有

LAMP websites
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"];
}

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

php mysql pdo prepared-statement
3个回答
76
投票

这里是一个使用 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;
}

8
投票

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

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

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)
{
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.