Reputation: 37494
Ok, i have data that i'm writing to JSON files with PHP, in each JSON file, there is to be ID, field1 and field2. Now, what i'm trying to work out is what is the best method for writing to a new file but with an autoincremented ID from the last file written to? Do i read all of the files and work out the highest number or is there a better method? And also, what names shall i give to each JSON file?
This is my code so far (note, ID field not yet implemented):
$data[] = $_POST['data'];
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
Upvotes: 0
Views: 766
Reputation: 132098
You can do this two ways that I can think of, off the top of my head.
Use MySQL for the auto incrementing. Create a table that only has a primary key with auto_increment set. Insert a new record into the db and use the last insert id.
Use a semaphore (of sorts) to store the last id in a system file. Before you save your json, you ensure the the semaphore is NULL, create a file (semaphore.txt), open the id file (current_id.txt or something), increment the number, save it and delete the semaphore.txt file. If the semaphore file exits, sleep for some time, and retry with a total timeout, or max loop count.
If you go with option 1, you can just add another field that contains the name of the file you are saving and use uniqid (or similar) for generating a filename. Of course, you could just use <id>.json
Upvotes: 1