php 如何使用php转换json中的mysql数据库表数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9785649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:37:30  来源:igfitidea点击:

How to convert mysql data base table data in json using php

phpmysqljson

提问by Aftab Ali

How to convert MySQL data base table into JSON data using PHP. Is there any way to do this?

如何使用 PHP 将 MySQL 数据库表转换为 JSON 数据。有没有办法做到这一点?

Below is the php code I am using:

下面是我正在使用的php代码:

<?php 
$host = "emriphone.db.6420177.hostedresource.com"; 
$user = "emriphone"; 
$pass = "Light12-"; 
$database = "emriphone"; 

$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host."); 
mysql_select_db($database, $linkID) or die("Could not find database."); 

$sth = mysql_query("SELECT * FROM ProviderAppointmentListings");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
   $rows[] = $r;
}
print json_encode($rows);
?>

回答by Mariusz Jamro

Try like this:

像这样尝试:

$query = mysql_query("SELECT * FROM table");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
    $rows[] = $row;
}
print json_encode($rows);

If you don't have json_encodeadd this before the code above:

如果你没有json_encode在上面的代码之前添加这个:

if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\', '\/', '\n', '\t', '\r', '\b', '\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}

回答by Christofer Eliasson

I guess you mean the data in a MySQL-database table right?

我猜你的意思是 MySQL 数据库表中的数据对吗?

In that case, have a look at PHP's json_encode().

在这种情况下,请查看 PHP 的json_encode()

You can fetch the data from the db into an array and then covert it to JSON.

您可以将数据库中的数据提取到一个数组中,然后将其转换为 JSON。

回答by wdog

put the resultset of the query into an array and then use json_encode

将查询的结果集放入一个数组中,然后使用 json_encode

$sql="Select * from table";
$l= array();
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
  $l[] = $row;
}
$j = json_encode($l);
echo $j;

you may use id table as index of the array.

您可以使用 id 表作为数组的索引。

回答by shri

<?php
    $username = "user_name"; 
    $password = "password";   
    $host = "url";
    $database="database";

    $server = mysql_connect($host, $username, $password);
    $connection = mysql_select_db($database, $server);

    $myquery = "SELECT date,close FROM data2";
    echo "hi";
    $query = mysql_query($myquery);

    if ( ! $query ) {
        echo mysql_error();
        die;
    }    
    $data = array();    

    for ($x = 0; $x < mysql_num_rows($query); $x++) {
        $data[] = mysql_fetch_assoc($query);
    }

    echo json_encode($data);     

mysql_close($server);

?>

This code converts your mysql data in phpmyadmin to json. Works perfect

此代码将您在 phpmyadmin 中的 mysql 数据转换为 json。工作完美

回答by Masoud Siahkali

using this code :

使用此代码:

json_encode($array)

for example :

例如 :

public function SELECT($tableName,$conditions){

      $connection = mysqli_connect($hostname, $userName, $password,$dbName);
      try {

        if (!$connection)
            die("Connection failed: " . $connection->connect_error);
        else
        {
            $qry = "";
            if(!$this->IsNullOrEmptyString($conditions))
               $qry = "SELECT * FROM `".$tableName."` WHERE ".$conditions;
            else
               $qry = "SELECT * FROM `".$tableName."`";

            $result = mysqli_query( $connection, $qry);
            if($result) {
                $emparray = array();
                while($row =mysqli_fetch_assoc($result))
                    $emparray[] = $row;

                echo(json_encode($emparray));           
            }
            else
                echo(mysqli_error($connection));       
            } 
            mysqli_close($connection); 
      } catch(Exception $ex) {
          mysqli_close($connection);
          echo($ex->getMessage());
      }  
 }

回答by neuromancer

As long as you are using MySQL server 5.7 or later, you can produce JSON data by using just SQL and nothing more, that is, you need PHP just to pass the SQL and get the JSON result. For example:

只要你使用 MySQL server 5.7 或更高版本,你就可以只使用 SQL 生成 JSON 数据,仅此而已,也就是说,你只需要 PHP 来传递 SQL 并获取 JSON 结果。例如:

SELECT JSON_OBJECT( 'key1', column1,
                    'key2', JSON_OBJECT('key3', column2)) as fοο;

There is more that JSON_OBJECT! Please check this page: https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

还有更多JSON_OBJECT!请查看此页面:https: //dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

回答by Neoistone

<?php
$username = "user_name"; 
$password = "password";   
$host = "url";
$database="database";

$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);

$myquery = "SELECT date,close FROM data2";
echo "hi";
$query = mysql_query($myquery);

if ( ! $query ) {
    echo mysql_error();
    die;
}    
$data = array();    

for ($x = 0; $x < mysql_num_rows($query); $x++) {
    $data[] = mysql_fetch_assoc($query);
}

echo json_encode($data);     
mysql_close($server);

?>

?>