nyamuk91 nyamuk91 - 18 days ago 6
HTML Question

How to print table data index in RecursiveArrayIterator

I want to print a table with index and I'm currently new to PDO and recursive table printing (is that what it's called?). I found a sample code to do that but it didn't print the index together with the data. So I modified the code to include index. However, I'm using Global Variable and from what I understand, it is a bad practice to use global variable. Is that so? Any other way to do it?

<?php

echo "<table id='DataTable1' class='display' cellspacing='0' width='100%'>";
echo "<tr><th>No</th><th>Name</th><th>Phone</th><th>Email</th><th>Guest</th><th>Attendance</th></tr>";

$i = 1;

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() {
$index = $GLOBALS['i'];
echo "<tr><td>$index</td>";
}

function endChildren() {
echo "</tr>" . "\n";
$GLOBALS['i']++;
}
}

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT guestName, guestPhone, guestEmail, guestGuest, attendance FROM rsvp_list");
$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>";
?>

Answer

the best practice is apparently NOT to use no recursive iterators to output HTML tables at all. Some strange guy put it up on the web page and for some reason many people started to make their lives ten times more complicated.

While to output an HTML table one don't need no iterators at all, let alone recursion.

<?php

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT guestName, guestPhone, guestEmail, guestGuest, attendance FROM rsvp_list";
$data = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); 

?>
<table id='DataTable1' class='display' cellspacing='0' width='100%'>
    <tr><th>No</th><th>Name</th><th>Phone</th><th>Email</th><th>Guest</th><th>Attendance</th></tr>
    <? foreach ($data as $index => $row): ?>
        <tr>
            <td><?=$index+1?></td>
            <? foreach ($row as $value): ?>
                <td style='width:150px;border:1px solid black;'><?=$value?></td>
            <? endforeach ?>
        </tr>
    <? endforeach ?>
</table>

this code is ten times cleaner, shorter, and saner.

Comments