Skip to content

Instantly share code, notes, and snippets.

@westonwatson
Created September 23, 2012 08:29
Show Gist options
  • Save westonwatson/3769358 to your computer and use it in GitHub Desktop.
Save westonwatson/3769358 to your computer and use it in GitHub Desktop.
SIMPLE JSON FLAT FILE DATABASE
<?php
if ($_GET['id']) push_out( read_record($_GET['id']));
if ($_POST){
if (is_numeric($_POST['id'])){
//update record
push_out(json_encode(save_record($_POST)));
}elseif(is_numeric($_POST['_delete_record'])){
//remove record
push_out(json_encode(remove_record($_POST['_delete_record'])));
}elseif(!$_POST['id']){
//add record
push_out(json_encode(save_record($_POST)));
}
}
function push_out($data){
die($data);
}
function data_path($id){
//path to file
return "./_data_record_{$id}";
}
function save_record($data){
if (!is_numeric($data['id'])) $data['id'] = new_id();
file_put_contents(data_path($post['id']),json_encode($data));
return $data['id'];
}
function remove_record($id){
if (unlink(data_path($id))) return $id;
}
function read_record($id){
return file_get_contents(data_path($id));
}
function new_id(){
return round(time()*rand());
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment