How to use PDO to fetch results array in PHP?

前端 未结 3 947
心在旅途
心在旅途 2020-11-22 10:09

I\'m just editing my search script after reading up on SQL injection attacks. I\'m trying to get the same functionality out of my script using PDO instead of a regular mysql

3条回答
  •  有刺的猬
    2020-11-22 10:27

    There are three ways to fetch multiple rows returned by PDO statement.

    The simplest one is just to iterate over PDOStatement itself:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // iterating over a statement
    foreach($stmt as $row) {
        echo $row['name'];
    }
    

    another one is to fetch rows using fetch() method inside a familiar while statement:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // using while
    while($row = $stmt->fetch()) {
        echo $row['name'];
    }
    

    but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // fetching rows into array
    $data = $stmt->fetchAll();
    

    or, if you need to preprocess some data first, use the while loop and collect the data into array manually

    $result = [];
    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // using while
    while($row = $stmt->fetch()) {
        $result[] = [
            'newname' => $row['oldname'],
            // etc
        ];
    }
    

    and then output them in a template:

    Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

提交回复
热议问题