View Contacts (view_contacts.php) Code Example

Copy the code below:

<?php include 'includes/secure_user.php'; ?>

<?php
require_once 'C:/inetpub/config_nm.php'; // Load DB credentials

$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";

try {
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch all contact messages
    $sql = "SELECT id, first_name, last_name, email, subject, message, submitted_at FROM contact_messages ORDER BY submitted_at DESC";
    $stmt = $pdo->query($sql);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>


<!DOCTYPE html>
<html lang="en">
<?php 
  $pageTitle = "View Contacts"; 
  include 'includes/head.php';  
?> 
       
<body>
 <?php include 'includes/navbar.php'; ?>

<div class="container mt-5">
    <h2 class="mb-4">View Contact Messages
	<i class="bi bi-mailbox2 bg-danger text-black p-1 rounded"></i>
	</h2>

    <?php if (count($messages) === 0): ?>
        <div class="alert alert-info">No messages found.</div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-striped table-bordered align-middle">
                <thead class="table-light">
                    <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Subject</th>
                        <th scope="col">Message</th>
                        <th scope="col">Submitted At</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($messages as $msg): ?>
                        <tr>
                            <td><?= htmlspecialchars($msg['id']) ?></td>
                            <td><?= htmlspecialchars($msg['first_name'] . ' ' . $msg['last_name']) ?></td>
                            <td><?= htmlspecialchars($msg['email']) ?></td>
                            <td><?= htmlspecialchars($msg['subject']) ?></td>
                            <td><?= nl2br(htmlspecialchars($msg['message'])) ?></td>
                            <td><?= htmlspecialchars($msg['submitted_at']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php include 'includes/scripts.php'; ?>
</body>
</html>