To retrieve and display data in JSON format from a database using PDO in PHP, you can follow these steps:
<?php
$dns = 'mysql:host=localhost;dbname=your_database_name';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dns, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
$sql = "SELECT * FROM your_table_name";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<?php
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
?>
<?php
$jsonData = json_encode($result);
?>
<?php
header('Content-Type: application/json');
?>
<?php
echo $jsonData;
?>
This code will retrieve all the data from the specified table and display it in JSON format when executed. Adapt the code by replacing "your_database_name", "your_username", "your_password", and "your_table_name" with your actual values.