How to fetch and display query results from a database using PDO in PHP?

To fetch and display query results from a database using PDO in PHP, you can follow these steps:

  1. Connect to the database using PDO:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
  1. Prepare and execute a SQL query using PDO:
<?php $sql = "SELECT * FROM your_table"; $stmt = $conn->prepare($sql); $stmt->execute(); ?>
  1. Fetch the query results and display them:
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "Column 1: " . $row['column1'] . "<br>"; echo "Column 2: " . $row['column2'] . "<br>"; // ... and so on } ?>

Putting it all together, here's a complete example:

<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; $sql = "SELECT * FROM your_table"; $stmt = $conn->prepare($sql); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "Column 1: " . $row['column1'] . "<br>"; echo "Column 2: " . $row['column2'] . "<br>"; // ... and so on } } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>

Replace "username", "password", "database", "your_table", "column1", "column2", etc. with your actual values.