PHP의 PDO를 통해 MySQL 쿼리를 어떻게 반복합니까?
문제
나는 천천히 내 모든 것을 움직입니다 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"];
}
분명히 '다른 것'은 역동적 일 것입니다.
해결책
다음은 PDO를 사용하여 DB에 연결하고 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;
다른 팁
에 따르면 PHP 문서 다음을 수행 할 수 있어야한다고 말합니다.
$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $results)
{
echo $results["widget_name"];
}
나는 전문가는 아니지만 이것은 효과가 있어야합니다.
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)
{
...
}
제휴하지 않습니다 StackOverflow