如何在php中编写mysql查询以获取json格式输出

时间:2016-06-03 12:42:51

标签: php mysql json

我已经在php文件中编写了代码来连接数据库并获取所请求的数据。

  <?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);

  ?>

我以数组格式获取输出,我想以json格式输出。如何更改代码,请帮助我。

4 个答案:

答案 0 :(得分:0)

您需要使用php json_encode()方法。请检查php doc for json_encode here

答案 1 :(得分:0)

使用json_encode

我认为您正在使API返回JSON字符串,请确保将其作为JSON响应而不是HTML返回。这是一个很好的做法:)

要将JSON字符串作为JSON响应返回,您可以执行以下操作。

<?php

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

?>

答案 2 :(得分:0)

创建数组或结果并使用json_encode

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

echo json_encode($subject);

答案 3 :(得分:0)

你必须使用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);
           }
?>