我想打印一个包含索引的表格,我目前还不熟悉PDO和递归表格打印(就是它的名称?)。我发现了一个示例代码,但它并未将索引与数据一起打印出来。所以我修改了代码以包含索引。但是,我使用全局变量,而据我所知,使用全局变量是一种不好的做法。是这样吗?任何其他方式来做到这一点?如何在RecursiveArrayIterator中打印表格数据索引
<?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>";
?>
*最佳做法*是基于意见的,不属于此处。请阅读如何在Stackoverflow上[问]问题。 – Xorifelse
@Xorifelse我应该将主题重命名为“如何在RecursiveArrayIterator PHP PDO中打印表数据索引”呢? – nyamuk91
您已经在标记“PHP”和“PDO”了。那时他们不属于标题。 – Xorifelse