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

时间:2012-03-20 11:12:01

标签: php mysql json

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

以下是我正在使用的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);
?>

7 个答案:

答案 0 :(得分:13)

试试这样:

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

如果您没有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) . '}';
    }
  }
}

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

将查询的结果集放入数组中,然后使用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;

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

答案 3 :(得分:0)

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

?>

此代码将phpmyadmin中的mysql数据转换为json。完美无缺

答案 4 :(得分:0)

使用此代码:

json_encode($array)

例如:

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

答案 5 :(得分:0)

只要您使用MySQL服务器5.7或更高版本,您就可以仅使用SQL生成JSON数据,也就是说,您需要PHP才能传递SQL并获取JSON结果。例如:

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

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

答案 6 :(得分:-2)

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

?>