PHP使用输出从mySql查询问题生成Json

时间:2017-12-11 11:14:28

标签: php json

我正在尝试使用mysql表中的数据通过查询生成一个json文件。

这是:

<?php 

$servername = "localhost";
$username = "myuser";
$password = "mypass";
$dbname = "mydatabase";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);

$json_data = json_encode($result);
file_put_contents('myfile.json', $json_data);


?> 

但它产生了这个,而不是实际的数据:

{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

表字段为:id,title和name

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

您必须先获取所有记录,然后对数据进行编码。

转换: -

$json_data = json_encode($result);

要: -

$json_data = json_encode(mysqli_fetch_all($result,MYSQLI_ASSOC));

你会很高兴

参考: - mysqli_result::fetch_all

答案 1 :(得分:1)

您需要获取所有列名称,如下所示:

<?php 

$servername = "localhost";
$username = "myuser";
$password = "mypass";
$dbname = "mydatabase";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_array($result);  // Check the function here.
$json_data = json_encode($row);
file_put_contents('myfile.json', $json_data);


?>