To fetch and display query results from a database using PDO in PHP, you can follow these steps:
<?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();
}
?>
<?php
$sql = "SELECT * FROM your_table";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<?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.