2008-10-01 9 views
22

Ich gehe langsam alle meine LAMP websites von mysql_ Funktionen zu PDO Funktionen und ich habe meine erste Mauer geschlagen. Ich weiß nicht, wie man Ergebnisse mit einem Parameter durchläuft. Ich bin gut mit der folgenden:Wie durchlaufe ich eine MySQL-Anfrage über PDO in PHP?

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

Allerdings, wenn ich so etwas wie dies tun wollen:

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

Offensichtlich ist die ‚etwas anderes‘ wird dynamisch sein.

Antwort

58

Hier ist ein Beispiel für die Verwendung von PDO mit einer DB zu verbinden, um Exceptions anstelle von PHP-Fehlern zu werfen (hilft bei der Fehlersuche) und parametrisierte Anweisungen anstatt dynamische Werte in die Abfrage selbst zu übernehmen empfohlen):

// $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; 
5

der PHP documentation Laut ist sagt Sie in der Lage, die folgenden sein sollte zu tun:

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

Ich bin kein Experte, aber das sollte funktionieren.

+3

Dies kümmert sich nicht um die "etwas anderes", die dynamisch sein könnte. Vorbereitete Abfragen wie von Shabbyrobe dargestellt ist die Antwort. – DGM

+5

@DGB, Darryls "etwas anderes" aus dem Beispiel der ursprünglichen Frage. Die Frage hat nichts mit dem dynamischen Assemblieren von Abfragen zu tun, sondern mit dem Iterieren der Ergebnisse einer Abfrage. Was er richtig beantwortet hat. Obwohl ich stimme zu, dass Shabbyrobe eine * bessere * Antwort gegeben hat. –

+0

yup, das ist definitiv richtig und kürzer. – andyk

3

Wenn Sie die foreach-Syntax mögen, können Sie die folgende Klasse verwenden können:

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

}

zu u Dann se it:

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