반응형
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"];
}
분명히 '다른 것'은 역동적일 것입니다.
다음은 DB에 연결하기 위해 PDO를 사용하고 pph 오류 대신 예외를 던지도록 지시하는 예이며 쿼리에 동적 값을 대입하는 대신 매개 변수화된 문을 사용하는 예입니다(매우 권장됨).
// 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;
}
PHP 문서에 따르면 다음 작업을 수행할 수 있어야 합니다.
$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $row) {
echo $row["widget_name"];
}
각 구문이 마음에 들면 다음 클래스를 사용할 수 있습니다.
// 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)
{
...
}
언급URL : https://stackoverflow.com/questions/159924/how-do-i-loop-through-a-mysql-query-via-pdo-in-php
반응형
'programing' 카테고리의 다른 글
자바스크립트에서 동등한 것에 대한 부정적인 뒤보기 (0) | 2023.10.29 |
---|---|
오류 1064:SQL 구문에 오류가 있습니다. MariaDB 서버 버전에 해당하는 설명서에서 다음에 사용할 올바른 구문을 확인하십시오. (0) | 2023.10.29 |
C에서 : 연산자의 사용 (0) | 2023.10.29 |
우커머스에서 날짜별로 사용자 주문을 받는 방법은? (0) | 2023.10.29 |
MySQL: 둘 이상 발생한 행 선택 (0) | 2023.10.29 |