How does this sentence prepared in PDO in PHP work?

0

I am reading about PDO and prepared sentences, I got this way of selecting data from the database, I would like someone to explain to me because I do not understand all the functions very well, especially the declared class and the recursiveIterator Iterator, I am used to working oriented to objects or procedures:

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator { 
    function __construct($it) { 
        parent::__construct($it, self::LEAVES_ONLY); 
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() { 
        echo "<tr>"; 
    } 

    function endChildren() { 
        echo "</tr>" . "\n";
    } 
} 

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
    
asked by Victor Alvarado 25.05.2017 в 01:26
source

1 answer

3

The declaration of the TableRows class inherits from the RecursiveIteratorIterator class and you can make use of public and protected methods.

This is useful for the definition and abstraction of the functionality and allows the implementation of additional functionality in similar objects without the need to reimplement all the shared functionality.

Of course you can overwrite some methods depending on the logic to be implemented.

The RecursiveIteratorIterator class is the class from which you inherit or over which you create an inherited class or subclass.

Basically, the Tablerows class is created from the definition of the RecursiveIteratorIterator class.

Here you have more information:

link

    
answered by 25.05.2017 в 01:50