Comment passer en revue une requête MySQL via PDO en PHP?
Question
Je déplace lentement tous mes sites Web LAMP
de fonctions mysql _
vers des fonctions PDO
et j'ai frappé mon premier mur de briques. Je ne sais pas comment parcourir les résultats avec un paramètre. Je vais bien avec ce qui suit:
foreach ($database->query("SELECT * FROM widgets") as $results)
{
echo $results["widget_name"];
}
Cependant, si je veux faire quelque chose comme ceci:
foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
echo $results["widget_name"];
}
Évidemment, le "quelque chose d'autre" sera dynamique.
La solution
Voici un exemple d'utilisation de PDO pour se connecter à une base de données, lui indiquant de lancer des exceptions au lieu d'erreurs php (vous aidera à déboguer), et d'utiliser des instructions paramétrées au lieu de substituer vous-même des valeurs dynamiques à la requête (hautement recommandé). ):
// $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;
Autres conseils
Selon la documentation PHP , vous devriez pouvoir le faire. faire ce qui suit:
$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $results)
{
echo $results["widget_name"];
}
Je ne suis pas un expert, mais cela devrait fonctionner.
Si vous aimez la syntaxe foreach, vous pouvez utiliser la classe suivante:
// 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);
}
}
}
Ensuite, pour l'utiliser:
foreach(new PDOStatementIterator($stmt) as $col => $val)
{
...
}