1

I am trying to generate a json file with the data from a mysql table via a query.

This is what have:

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


?> 

But it's generating this, instead of the actual data:

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

Table fields are: id, title and name

How can I fix this?

2
  • Is there only one record in the table that you want to send or can there be more? Commented Dec 11, 2017 at 11:19
  • 2
    just add like this $json_data = json_encode(mysqli_fetch_array($result)); Commented Dec 11, 2017 at 11:19

2 Answers 2

3

You have to fetch all records first and then encode the data.

So Convert:-

$json_data = json_encode($result);

To:-

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

And you will good to go

Reference:- mysqli_result::fetch_all

Sign up to request clarification or add additional context in comments.

Comments

0

You need to fetch with all column names like this:

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


?> 

1 Comment

For some reason it's still generating this: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}