Andrew G. Johnson
Andrew G. Johnson

Reputation: 26993

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

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.

Upvotes: 32

Views: 61868

Answers (3)

John K
John K

Reputation: 917

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)
{
    ...
}

Upvotes: 2

Darryl Hein
Darryl Hein

Reputation: 144947

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

Upvotes: 7

Shabbyrobe
Shabbyrobe

Reputation: 12628

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

Upvotes: 77

Related Questions