MySQL到JSON,只加载第一行

时间:2015-12-09 07:31:01

标签: php mysql json file

我尝试使用MySQL从表中获取所有行并将其存储为JSON文件。现在,存储在JSON文件中的唯一内容是表中的第一行。

以下是代码:

$sql_query = "SELECT * FROM table"; 
$res_sql = mysql_query($sql_query) or die(mysql_error());
$arr = array();


if(mysql_num_rows($res_sql) > 0){

    while($row_sql = mysql_fetch_assoc($res_sql)){

        $arr =  $row_sql;

        $json = json_encode($arr);
        $file = 'table.json';
        file_put_contents($file, $json);

        }



    }  

2 个答案:

答案 0 :(得分:3)

$sql_query = "SELECT * FROM table"; 
$res_sql = mysql_query($sql_query) or die(mysql_error());
$arr = array();


if(mysql_num_rows($res_sql) > 0){

    while($row_sql = mysql_fetch_assoc($res_sql)){

        $arr[] =  $row_sql;

    }

     $json = json_encode($arr);
     $file = 'table.json';
     file_put_contents($file, $json);    
} 

在循环外设file_put_contents

答案 1 :(得分:0)

尝试这样: -

 while($row_sql = mysql_fetch_assoc($res_sql)){

            $arr[] =  $row_sql;
     }
    $json = json_encode($arr);
    $file = 'table.json';
    file_put_contents($file, $json);