如何在PHP(PDO)中查询并展示SQL表的所有行?
Hey there! The problem with your current code is that fetch(PDO::FETCH_ASSOC) only grabs a single row from your query results. To get all the admin jail entries for the specified account, you'll need to adjust both your data-fetching function and your display code. Here's how to fix it step by step:
1. Update the Data-Fetching Function (function.php)
Replace fetch() with fetchAll() — this will return an array containing every matching row instead of just one.
function getCharacterAdminJails($account_id) { global $connection; $stmt = $connection->pdo->prepare("SELECT * FROM adminjails WHERE jailed_accountID = :account_id"); $stmt->bindParam(":account_id", $account_id); $stmt->execute(); // Use fetchAll to retrieve all matching rows $adminjail_data = $stmt->fetchAll(PDO::FETCH_ASSOC); return $adminjail_data; }
2. Modify the Display Code (example.php)
Now that $adminjail_data is an array of rows, you need to loop through it with foreach to generate a table row for each entry. I also added a check to handle empty result cases for better user experience:
<table class="table table-hover"> <tr> <th>Admin neve:</th> <th>Indok:</th> <th>Perc:</th> <th>Időpont:</th> </tr> <?php if (!empty($adminjail_data)): ?> <?php foreach ($adminjail_data as $jail): ?> <tr> <td><?= htmlspecialchars($jail["jailed_admin"]); ?></td> <td><?= htmlspecialchars($jail["jailed_reason"]); ?></td> <td><?= htmlspecialchars($jail["jailed_ido"]); ?></td> <td><?= htmlspecialchars($jail["jailed_idopont"]); ?></td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td colspan="4">Nincs található admin büntetés ehhez a fiókhoz.</td> </tr> <?php endif; ?> </table>
Quick Security Tip:
I added htmlspecialchars() to each output value — this escapes any user-provided content and helps prevent XSS attacks. It's a simple but important practice whenever you're displaying database data on a webpage.
内容的提问来源于stack exchange,提问作者ianlot

