gpt4 book ai didi

php - 将Mysql数据插入Json文件不起作用

转载 作者:行者123 更新时间:2023-11-29 23:48:59 28 4
gpt4 key购买 nike

我有一个脚本不起作用,我希望你们中的一些开发人员知道解决方案。

<?php
//Create Database connection
$db = mysql_connect("localhost","d","d");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}

//Select the Database
mysql_select_db("d",$db);

//Replace * in the query with the column names.
$result = mysql_query("select * from events", $db);

//Create an array
$json_response = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];

//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);

$file = 'events.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
// Write the contents back to the file
file_put_contents($file, $json_response);
//Close the database connection

?>

但是 events.json 是空的?有谁知道解决办法吗?

最佳答案

首先

echo json_encode($json_response);
file_put_contents($file, $json_response);

这不是写 json,你应该这样做

file_put_contents($file, json_encode($json_response));

也许这是问题所在,您无法将数组写入文件。

第二,你是否缺少一些代码?

$current = file_get_contents($file);
// Append a new person to the file

我们没有看到要在此处附加的代码,您的代码只是用数组 $json_response (而不是 json 编码数组)替换内容。

关于php - 将Mysql数据插入Json文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25759912/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com