Lennox Sherwin
Lennox Sherwin

Reputation: 19

How to populate a html table using the data in a MySql table dynamically using PDO?

I am able to populate the fields by manually entering the table headings and table data. However i have a large table and I want to dynamically fetch the data from the table. Can someone give me a sample code on how this could be achieved? I want to do it by PDO method.

Upvotes: 0

Views: 88

Answers (1)

Mahesh
Mahesh

Reputation: 371

You may try this

 $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
 $sql = 'SELECT lastname, firstname, jobtitle 
    FROM employees
    ORDER BY lastname';

  $q = $pdo->query($sql);

  $q->setFetchMode(PDO::FETCH_ASSOC);
  <table class="table table-bordered table-condensed">
<thead>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Job Title</th>
    </tr>
</thead>
<tbody>
    <?php while ($r = $q->fetch()): ?>
        <tr>
            <td><?php echo htmlspecialchars($r['lastname']) ?></td>
            <td><?php echo htmlspecialchars($r['firstname']); ?></td>
            <td><?php echo htmlspecialchars($r['jobtitle']); ?></td>
        </tr>
    <?php endwhile; ?>
</tbody>

Upvotes: 1

Related Questions