如何通过PHP中的PDO循环MySQL查询?

时间:2022-09-25 16:00:37

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:

我正在慢慢地将我的所有LAMP网站从mysql_功能移动到PDO功能,我已经打到了我的第一个砖墙。我不知道如何使用参数循环结果。我对以下情况很满意:

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.

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

3 个解决方案

#1


62  

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):

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

// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);

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

// 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 place holders 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();
if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $products[] = $row;
    }
}

// set PDO to null in order to close the connection
$pdo = null;

#2


5  

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

根据PHP文档说你应该能够做到以下几点:

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

I'm no expert, but this should work.

我不是专家,但这应该有效。

#3


3  

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

如果您喜欢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);
        }
    }

}

}

Then to use it:

然后使用它:

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

#1


62  

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):

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

// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);

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

// 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 place holders 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();
if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $products[] = $row;
    }
}

// set PDO to null in order to close the connection
$pdo = null;

#2


5  

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

根据PHP文档说你应该能够做到以下几点:

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

I'm no expert, but this should work.

我不是专家,但这应该有效。

#3


3  

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

如果您喜欢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);
        }
    }

}

}

Then to use it:

然后使用它:

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