PHP Classes

File: Index.php

Recommend this page to a friend!
  Classes of Ahmed Abdulla   PHP Database table to JSON   Index.php   Download  
File: Index.php
Role: Example script
Content type: text/plain
Description: Main page
Class: PHP Database table to JSON
Convert the records of a database table to JSON
Author: By
Last change:
Date: 9 months ago
Size: 884 bytes
 

Contents

Class file image Download
<?php
// Step 1: Establish a database connection
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die(
"Connection failed: " . $conn->connect_error);
}

// Step 2: Fetch data from the table
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

if (
$result->num_rows > 0) {
   
// Step 3: Convert data into JSON format
   
$data = array();
    while (
$row = $result->fetch_assoc()) {
       
$data[] = $row;
    }

   
$json_data = json_encode($data);

   
// Step 4: Output the JSON data
   
header('Content-Type: application/json');
    echo
$json_data;
} else {
    echo
"No records found.";
}

// Close the database connection
$conn->close();
?>