Skip to content

How to fetch data using pdo in PHP?

require_once 'dbconfig.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    $sql = 'SELECT lastname,
               FROM employees
              ORDER BY lastname';

    $q = $pdo->query($sql);
} catch (PDOException $e) {
    die("Could not connect to the database $dbname :" . $e->getMessage());
<!DOCTYPE html>
        <title>PHP MySQL Query Data Demo</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <div id="container">
            <table class="table table-bordered table-condensed">
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Job Title</th>
                    <?php while ($row = $q->fetch()): ?>
                            <td><?php echo htmlspecialchars($row['lastname']) ?></td>
                            <td><?php echo htmlspecialchars($row['firstname']); ?></td>
                            <td><?php echo htmlspecialchars($row['jobtitle']); ?></td>
                    <?php endwhile; ?>
See also  Python code snippet - How to find second maximum element of an array ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.