我正在尝试使用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);
}
}
$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
这样尝试:-
while($row_sql = mysql_fetch_assoc($res_sql)){
$arr[] = $row_sql;
}
$json = json_encode($arr);
$file = 'table.json';
file_put_contents($file, $json);