How to retrieve and display data in JSON format from a database using PDO in PHP?

To retrieve and display data in JSON format from a database using PDO in PHP, you can follow these steps:

  1. Establish the database connection using PDO:
<?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(); } ?>
  1. Prepare and execute the SQL query to fetch data:
<?php $sql = "SELECT * FROM your_table_name"; $stmt = $pdo->prepare($sql); $stmt->execute(); ?>
  1. Fetch the data from the executed query and store it in an associative array:
<?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $result[] = $row; } ?>
  1. Convert the fetched data array into JSON format:
<?php $jsonData = json_encode($result); ?>
  1. Set appropriate headers to indicate that the response is in JSON format:
<?php header('Content-Type: application/json'); ?>
  1. Finally, echo or display the JSON data:
<?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.