简体   繁体   English

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

[英]How to convert mysql data base table data in json using php

How to convert MySQL data base table into JSON data using PHP. 如何使用PHP将MySQL数据库表转换为JSON数据。 Is there any way to do this? 有没有办法做到这一点?

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

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_encode add 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) . '}';
    }
  }
}
<?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. 此代码将phpmyadmin中的mysql数据转换为json。 Works perfect 工作完美

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());
      }  
 }

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. 只要您使用MySQL服务器5.7或更高版本,您就可以使用SQL而不再生成JSON数据,也就是说,您需要PHP才能传递SQL并获取JSON结果。 For example: 例如:

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

There is more that JSON_OBJECT ! JSON_OBJECT还有更多! Please check this page: https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html 请查看此页面: https//dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

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. 您可以将db中的数据提取到数组中,然后将其转换为JSON。

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表作为数组的索引。

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

?> ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM