programing

PHP에서 PDO를 통해 MySQL 쿼리를 루프하려면 어떻게 해야 합니까?

codeshow 2023. 10. 29. 20:02
반응형

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

반응형