Jump to content

Write multiple json files in MySql loop


piearcy
Go to solution Solved by mac_gyver,

Recommended Posts

I need multiple json files written by their ID number. I call the id separately and also include it in the json file I'm writing. But when I'm writing I'm writing ALL the records in each .json file and not the individual records. 

 

I know I'm just overlooking something but anyone?

 

Here's the code. 

while ($row = $result->fetch_assoc()) {
   $myArray[] = $row;
   $message = json_encode(array($myArray));
   $id = $row['id'];
   $myfile = fopen("message/$id.json", "w") or die("Unable to create file!");
   fwrite($myfile, $message);
   fclose($myfile);
}

Thanks

Link to comment
Share on other sites

Because you're continuously adding to an array on every iteration. $myArray[] = $row this pushes $row into the array on every iteration. At the end of the loop, $myArray contains the entire contents of your database result.

 

That variable isn't even necessary. Just do:

$message = json_encode(array($row));
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.