0

i have written code in php file that to connect to database and get the requested data .

  <?php
 // 1. Create a database connection
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "root";
 $dbname = "widget_corp";
   $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
  // Test if connection succeeded
   if(mysqli_connect_errno()) {
     die("Database connection failed: " . 
     mysqli_connect_error() . 
     " (" . mysqli_connect_errno() . ")"
   );
 }
       $query  = "SELECT * ";
       $query .= "FROM subjects ";
       $query .= "WHERE visible = 1 ";
       $query .= "ORDER BY position ASC";
       $result = mysqli_query($connection, $query);
       $subject = mysqli_fetch_assoc($result);
      print_r($subject);

  ?>

i am getting the output in array format ,i want to get the out put in json format.how to change the code ,please help me .

4 Answers4

0

You need to use php json_encode() method. Please check php doc for json_encode here

Talha Malik
  • 1,509
  • 3
  • 22
  • 44
0

Use json_encode:

I suppose you're making API to return JSON string, make sure you return it as a JSON response instead of HTML. It's a good practice :)

To return JSON string as a JSON response, You can do the following.

<?php

     header('Content-Type: application/json');
     echo json_encode($subject);

?>
Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

create a array or results and use json_encode.

$subject =  array();
while($row = $result->fetch_assoc() ){
   $subject[] = $row;
}

echo json_encode($subject);
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

You have to use json_encode($subject).

    <?php
     // 1. Create a database connection
     $dbhost = "localhost";
     $dbuser = "root";
     $dbpass = "root";
     $dbname = "widget_corp";
       $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
      // Test if connection succeeded
       if(mysqli_connect_errno()) {
         die("Database connection failed: " . 
         mysqli_connect_error() . 
         " (" . mysqli_connect_errno() . ")"
       );
     }
           $query  = "SELECT * ";
           $query .= "FROM subjects ";
           $query .= "WHERE visible = 1 ";
           $query .= "ORDER BY position ASC";
           $result = mysqli_query($connection, $query);
           $subject = mysqli_fetch_assoc($result);

           if($subject)
           {                 
                 $json_subject = json_encode($subject);
                 print_r($json_subject);
           }
?>
Bhavin
  • 2,070
  • 6
  • 35
  • 54