How to use PDO to fetch results array in PHP?

前端 未结 3 948
心在旅途
心在旅途 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:

    <ul>
    <?php foreach($data as $row): ?>
        <li><?=$row['name']?></li>
    <?php endforeach ?>
    </ul>
    

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

    0 讨论(0)
  • 2020-11-22 10:29
    $st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10"); 
    
    0 讨论(0)
  • 2020-11-22 10:34

    Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

    Code sample for fetchAll, from the PHP documentation:

    <?php
    $sth = $dbh->prepare("SELECT name, colour FROM fruit");
    $sth->execute();
    
    /* Fetch all of the remaining rows in the result set */
    print("Fetch all of the remaining rows in the result set:\n");
    $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
    print_r($result);
    

    Results:

    Array
    (
        [0] => Array
            (
                [NAME] => pear
                [COLOUR] => green
            )
    
        [1] => Array
            (
                [NAME] => watermelon
                [COLOUR] => pink
            )
    )
    
    0 讨论(0)
提交回复
热议问题