Online Magazine with Flat File Database
For our second example, we are going to create an online magazine.
The magazine will be coded in PHP and the database will consist of 3 arrays: 2 tw-dimensional array: 'stories' and 'authors' and a one-dimensional array tags. As in the first example, commas are used to delimit the one-dimensional array and 3-character strings are used to delimit the two-dimensional arrays. These arrays are all stored as text files, with 'stories' and 'authors' inside folders, while the tags are a single text file.
Section 1: Defining the Database:
This file defines the field delimiter and record fields:
CATSTACK/inc/database-definitions.php ▾
<?php
//Field Delimiters
$dl1 = "%!%";
$dl2 = "%#%";
//Record keys
$storyrecordkeys = array ("title", "author", "date", "text","issue","image") ;
$authorrecordkeys = array ('name', 'phone', 'address', 'email', 'description', 'image');
?>
This folder holds the 'author' records:
CATSTACK/data/authors
bob-cat.txt ▾
Bob Cat%!%513 418-1480%!%22 Fishtail Circle, Felinia OH 45150%!%bobcat@catmail.com%!%Public Relations Director, Fancy Feasties Industries Worldwide%!%bobcat.jpg
horace.txt ▾
Horace%!%(513) 418-1480%!%257 Felinia Blvd, Felinia Ohio%!%Horace222@catmail.com%!%Director of Felinia Small Prey Center%!%
miss-kitty.txt ▾
Miss Kitty%!%513 418-1480%!%99 Catgrass Lane, Felinia OH 45150%!%Mkitty@meowmail.com%!%Senior Editor, Catstack Magazine%!%misskitty.JPG
priscilla-paddypaws.txt ▾
Priscilla Paddypaws%!%513 418-1480%!%Big Stretch Lane%!%Ppaws@catmail.com%!%Chair, Etticat Department, Felinia University
professor-fluffy.txt ▾
Professor Fluffy%!%513 418-1480%!%12 Scratching Post Road, Apt 2b, Felinia, Ohio 45150%!%Fluffyone@feliniauniversity.org%!%Chair, History Department, Felinia University%!%Horace.jpg
squeekie.txt ▾
Squeekie%!%513 418-1480%!%178536 Tuna Treat Avenue%!%squeek@meowmail.com%!%Famous Influencer%!%squeekie.jpg
This folder holds the 'stories' records:
CATSTACK/data/stories
are-you-a-fish-cat-or-a-chicken-cat.txt ▾
Are you a Fish Cat or a Chicken Cat?%!%bob-cat%!%2024-05-23%!%Yes, dining preferences seem to fall into two groups - do you like fish or chicken? Fortunately, there are lots of choices out there and today, I'm going to review the best products for 2024 in both categories.
Fish:
Fancy Feasty, the perennial winner came in #1 again. However, Royal Canin, Iams and Blue Buffalo were considered marginally edible, at least in an emergency.
Chicken:
Again, Fancy Feasty was the favorite, with slightly honorable mentions to Royal Canin, Iams and Blue Buffalo, although our taste testers all came down with tummy aches after the experience.
(Note - Small would like to thank our sponsor, Fancy Feasty, for the gift of 8 million dollars to our Catnip for Everyone Fund and for inviting our entire editorial board on a fantastic vacation in Catalonia, Spain!)%!%2024-2%!%fish-or-checken.jpg
catnip-how-to-tell-if-you-are-an-addict.txt ▾
Catnip - How to Tell if You are an Addict%!%squeekie%!%2023-01-11%!%Catnip use is such a controversial issue. Some cats seem to enjoy a good roll in the nip after a hard day of work. Other cats just can't leave it alone. You will see them passed out in yards, chewed leaves all over their whiskers, glassy eyed and limp. <br> <br>There are many opinions - should catnip be an illegal substance? Should money be allocated for more addition treatment centers? Do we need more research? Education? Foundations? Fund raisers? Should we just forget the whole thing and take a nap?
Public policy is soo hard!%!%2024-2%!%addict.jpg
catnip-in-history.txt ▾
Catnip in History%!%professor-fluffy%!%2023-03-05%!%Did you know that catnip was first discovered by the cats of ancient Egypt? They found it useful during boring human religious services. Even though cats were the main attraction in the temples and it was nice to get treats (offerings), the priests talked too much. A little nip kept the temple cats on their toes for when platters of Nile trout came their way.
Later, Persian cats put Cyrus the Great into power so that he would conquer all the lands that produced the best nip. Later, Xerxes was assisted in conquering the Greeks by the cats of Sparta who were tired of catnip shortages. They were greatly rewarded for their efforts and even today, Persian cats are held in high esteem as extremely intelligent, though not very loyal.
Fast forward to the Russian Revolution when those Russian Blues backed the wrong side and managed to flee to the countryside when the Bolsheviks took over. However, today they are making a comeback and even feature prominently in Hollywood movies ("Cats and Dogs");%!%2024-2%!%catnip.jpg
controlling-the-litter-box.txt ▾
Controlling the Litter Box%!%miss-kitty%!%2024-07-02%!%Many cats are unsure about how to manage their litter boxes. I'm here to clear up some misunderstandings. The first thing to remember is it's not your job to keep it clean. It's their job. If they aren't doing their job, you have every reason to choose another spot to do your business. Don't go nuclear on them, just find a piece of floor close to the box that they will definitely see, and hopefully step in!!
Another tip - kick up as much litter as you like. It's not your job to keep in in the box. It's their job! Maybe they need to get a taller box. A light scatter of litter all around the box is a good training exercise to get them to comply.
More to come!%!%2024-1%!%misskitty.jpg
customer-service-is-overrated.txt ▾
Customer Service is Overrated%!%bob-cat%!%2023-07-02%!%Good customer service is not always to your advantage. If you can just pick up the phone any time and reach our support department, doesn't it make you wonder if maybe there's not much going on? But if you have to wait a while, that means the company is doing a lot of business and you are in line with a bunch of other customers. Or, the company is busy growing and expanding, so the support department hasn't kept up with the demand.
If there is a prominent display of a support phone number on the website, that's a terrible signal - it means the company is wasting resources on taking care of customer questions instead of concentrating on their prime directive - MAKE MORE MONEEEE!!
You, as a customer, will feel much better knowing that your needs are barely noticed by this successsful business, and that the employees all have much better things to do than answer the phone!%!%2024-1%!%Ralph-with-squishables.jpg
enjoying-the-outdoors.txt ▾
Enjoying the Outdoors%!%horace%!%2024-08-15%!%As an avid hunter and fishercat, I'm appalled at the low level of predatory skills exhibited by the younger generation. You kittens need to know how to hunt real prey, not just cat toys. To all you parents out there, sign them up for a summer class at the Felinia Small Prey Center where they can learn the survival skills our pioneer ancestors depended on - stalking, pouncing and chomping. Don't let your kittens grow up playing video games indoors -introduce them to the wild!%!%%!%outdoors.jpg
extreme-challenges.txt ▾
Extreme Challenges%!%miss-kitty%!%2024-08-15%!%This is a reprint from the Catstone Institute, but I feel it is important that our readers know how to deal with the situation.
"My name is Sylvester and I am forced to share my home with a creature so bizarre that I hardly have words to describe it. The humans call it an 'iguana' but I will refer to it as the Big Green Thing. It's as big as me and covered with spikes. Yes, pointy spikes from it's head to its tail. And it lives in the MY livingroom. On a log next to MY picture window.
"My only comfort comes from the fact that there is a glass wall between it and the rest of the house, so it can't get out and eat me! The humans are always feeding it and so far it's just vegetables, but with the teeth on that thing I expect it could eat a cat as well.
"However, I have discovered that I can have a bit of fun. It's easily annoyed. All I have to do is stroll past the glass a few times, kind of non-chalant, and it's gets all riled up. Sometimes it will jump down from the log and bob its head at me with a terrific angry glare in it's little beady eyes. "You can't get out of there, you idiot", I say, though I don't think it's smart enough to speak Cat.
"The point of this story is that no matter what you circumstances, you can 'reframe' the situation so that you have a little fun and your enormous ego gets even bigger!
Editor: I hope you got some inspiration from this case of extreme hardship. If Sylvester can deal with his problems, then living with a dog is not so bad.%!%%!%iguana.jpg
how-to-raise-successful-kittens.txt ▾
How to Raise Successful Kittens%!%miss-kitty%!%2024-07-02%!%Hey all you parents out there -
We know you are concerned about how your kittens will succeed in this uncertain economy. So , we are here to give some basic tips, that will help you in your quest to Raise Successful Kittens!
1. Forget about college - teach your kittens CUTENESS! According to famous psychologist Jordan Caterson, the best gift you can give your kittens it to make them irresistibly CUTE. Obliterate humans with the CUTE-ray, scramble their brains with weaponized ADORABLENESS. They will never know what hit them - they will give up their entire house, furniture and sleep schedule to make your kittens happy.
2. Hunting. Don't let your kittens get fat and lazy off cat food. Teach them some life skills. You never know when you will need to grab a bird from a back yard. Make hunting fun and they will always remember it fondly.
3. Teach them the TRUTH about dogs. Dogs are not our friends, no matter how nice they appear to be. Humans have a tendency to favor dogs, and there's a lot of rubbish out there about how dogs and cats can be buddies - make sure your kittens the basics: Dogs drool, cats rule!%!%2024-1%!%box.jpg
nappy-new-year.txt ▾
Nappy New Year!%!%squeekie%!%2023-01-09%!%Yes, I know you are fed up with New Years Resolutions that no one ever keeps past January. How many times have you taken out a membership at a health club only to stop going after a week.
Well, I'm here to tell you that there is one resolution that you should be keeping - Take More Naps! There are so many benefits from napping during the day, but the most important is that you can stay up late at night. That's when you have the most fun, anyway, jumping on countertops, running up and down stairs, knocking over lamps, and of course, meowing. There's nothing like a few meows at 4am for instant results! Watch your human servants thrash around in bed and try to go back to sleep. With practice, you should be able to get them into the kitchen with less than 5 meows.
But, in order to function at your optimal potential, you need to nap. All day!%!%%!%nappy.jpg
overcoming-tolerance.txt ▾
Overcoming Tolerance%!%miss-kitty%!%2024-08-15%!%I understand that some of my readers do not live in the best of circumstances. Some of you live with dogs and even manage to make the best of it. However, some of you (and you know who I'm talking about!), actually befriend these creatures. Get along with them, hang out on the same furniture, even let them lick you!!!
Srsly, friends, this is a terrible trend that can lead to nothing but a diminishing of our species superiority. Do you want you kittens playing with puppies? Out in the yard, getting muddy?!? They may even take up the habit of peeing under a bush. Horror!
Heed my warning - remember the wise wise words of the ancient sage - 'Cats rule, dogs drool'!!!%!%%!%barkleythedoggie.jpg
seven-habits-of-highly-effective-cats.txt ▾
Seven Habits of Highly Effective Cats%!%squeekie%!%2024-06-26%!%1. Don't just wait - make it happen! For example, it's 7am and the food dish has been empty for hours. Don't just wait around, jump on the bed, scratch at the door, use your words!
2. Focus on the outcome. For example, the humans are going shopping. You want them to return with a bag full of Fancy Feast. Block the door and hit them with a category 5 purr beam when they try and move you.
SNIPPET
3. Know your priorities. Dogs and little kids are not among them.
4. Whats best for you is also what's best for them. Make sure they know that.
5. Figure out what they are thinking so you can manipulate them better. This can be a challenge because human ears don't swivvel.
6. You are supposed to combine some of the other habits into this one. We haven't figured this out yet, but will keep you posted.
7. Sharpen your claws! That's what furniture is for. Don't get sidetracked by those silly scratching posts and cardboard thingies - go for the gold!!%!%2024-1%!%business-cat.jpg
seven-ways-to-get-a-fatter-tummy.txt ▾
Seven Ways to get a Fatter Tummy%!%priscilla-paddypaws%!%2024-07-02%!%It's a new year and as always, we want to provide you, our readers, with the BEST health and wellness advice. Enjoy our 11 tips on plumping up that tummy!
1. Meow for food in the middle of the night - they will feed you just to get some sleep.
2. Keep an eye on the table and the counters at all times. If people are in the kitchen, that's where you should be too.
3. Save your hairballs for food you don't like - people can be sooo dense.
4. Try some of those bugs around the house. Palmetto bugs aren't too bad and are fun to chase.
5. Sleep more!
6. Lay around more!
7. Only jump up on the table if it's worth it - ignore all vegetables!%!%%!%stampie.jpg
the-cat-inspired-business.txt ▾
The Cat-Inspired Business%!%bob-cat%!%2024-07-02%!%In the words of the great feline motivational speaker, Tony Robbyou,
"Money is just there for you to take it - don't pass up a single morsal!"
Hey Humans -
Want to make a lot of money? So you can spend it on CATS?
Try PurrPress!
Even humans can use the PurrPress CMS. With it's built-in ultra-fast, Google-snarking SEO secret sauce, you are guaranteed to launch your product into the meme-o-sphere, leverage your credulity and cat-a-pult your brand beyond the back of the sofa!!!
Never again try to figure out what a widget is or what happened to your images. You have better things to do with you pathetically limited brain power. Now you can just concentrate on making money for your Cats!
As you go about your day selling your product, keep the image of your happy, wealthy cats in your mind. Don't put up resistance to the wealth that they deserve!
Go forth and get RICH!!
Srsly!%!%2024-1%!%nippy.jpg
walking-your-person.txt ▾
Walking Your Person%!%priscilla-paddypaws%!%2024-07-02%!%Not all humans are intelligent enough to go for a walk with their cat, but a few are. They mostly need training. They want to be in charge and you have to firmly let them know they are not.
Here's a few tips to upgrade your human's performance:
- Find a spot under a bush and hunker down for a while. Force them to wait and wait and wait.
- Make a dash for a butterfly or a frog - catch them off balance and force them to run to keep up with you.
- Make mean faces and growl when their friends show up, especially if there is a dog. You can just ignore the bigger ones, but it's kind of fun to start chasing the really tiny ones! Embarrasses the human, too - fun!
- Get away from the leash - it's not that hard, especially on bumpy terrain. They will be trying to catch up with you but humans are sooo clumsy. Enjoy watching them try and catch you!%!%2023-4%!%Holly-in-grass3.jpg
what-is-money.txt ▾
What is Money?%!%squeekie%!%2023-01-19%!%<i>(Reprinted with permission from <a href = 'https://wealthycats.com'>Wealthy Cats Magazine)</a></i><br>
Hi Wealthy Cat Wannabees -
Let's talk about Money - do you know what Money is? Don't feel bad if you don't- it's not obvious. Here's what I found out from watching my humans over the years.
For one thing, they talk about Money all the time. Is Money another human? A god? An invisible force? Actually, yes - like in Star Wars - Money is <i> "an energy field created by all living things. It surrounds us and penetrates us; it binds the galaxy together."</i> - Thank you Obi-Wan
Sometimes it can manifest as an actual object. That green paper that humans carry around is a form on Money. It shows up on computer screens as little numbers. But mostly it's an invisible force. People think about Money all the time, but they can't see it.
Fortunately for you, cats have the ability to see things that are invisible to humans. If you put a little effort into it, you can see the streams of money that float by in the air. It's a little like humans seeing auras, only it's kind of sparkly.
Money accumulates in certain places in the house, like the kitchen and around anything new. Most of the stuff coming into the house has a lot of money around it. You just have to notice. After things have been around a while, the money fades away.
One of the best places to find a lot of Money is in empty shopping bags. Go inside and just soak it up. Doesn't it feel great! If a human gets a gift, the box is full of Money - get in that box! New clothes lying around are just spewing out Money - sprawl out and get comfortable - don't let any of that wealth get away!Make it a habit to always rub up against anything new- that way the Money rubs off on you.
If you diligently practice these habits, there is no limit to the amount of Money you can accumulate. Sometimes the humans will try to remove you from a good Money spot. Don't give up - jump right back into that box. Plop yourself down on the new expensive dress. Before you know it, you will be a Wealthy Cat!
So there, you now know what Money is, and how you can get some!%!%%!%with-mouse.jpg
why-do-dogs-exist.txt ▾
Why do Dogs Exist?%!%professor-fluffy%!%2024-05-22%!%This question has been pondered by many of the best minds in all of catstory. Many theories have been suggested, ranging from the deeply spiritual to the ridiculous. Here are some of them:
* They are here to test and challenge us so we can evolve to even higher levels of superiority
* They are here to test humans - only the most worthy humans are cat people - the lowly forms are dog people - useful information for us cats
* They were created by mistake - Ceiling cat got lazy one day and screwed up
* They were created by an evil entity to try and bring ruin to our noble species
* They evolved to fill a niche for slovenly, slobbering idiots - maybe there were'nt enough of that type in the ecosystem
* The most ridiculous is that they are our equals, just different - ha!%!%%!%ritchie.jpg
This file contains a list of 'tags':
CATSTACK/data/tags.txt ▾
health,philosophy,opinion,education,naps
Section 2: Relationships between records
As in Example 1, relationships between tables are established by 'maps' - two-dimensional arrays containing pairs of values.The 'story-author' map:
CATSTACK/data/maps/story-author-map.txt ▾
why-do-dogs-exist%#%professor-fluffy%#%
%!%what-is-money%#%squeekie%#%
%!%walking-your-person%#%priscilla-paddypaws%#%
%!%the-cat-inspired-business%#%bob-cat%#%
%!%seven-ways-to-get-a-fatter-tummy%#%priscilla-paddypaws%#%
%!%seven-habits-of-highly-effective-cats%#%squeekie%#%
%!%overcoming-tolerance%#%miss-kitty%#%
%!%nappy-new-year%#%squeekie%#%
%!%how-to-raise-successful-kittens%#%miss-kitty%#%
%!%extreme-challenges%#%miss-kitty%#%
%!%enjoying-the-outdoors%#%horace%#%
%!%customer-service-is-overrated%#%bob-cat%#%
%!%controlling-the-litter-box%#%miss-kitty%#%
%!%catnip-in-history%#%professor-fluffy%#%
%!%catnip-how-to-tell-if-you-are-an-addict%#%squeekie%#%
%!%are-you-a-fish-cat-or-a-chicken-cat%#%bob-cat%#%
The 'date-story' map:
CATSTACK/data/maps/date-story-map.txt ▾
2024-08-15%#%overcoming-tolerance%#%
%!%2024-08-15%#%extreme-challenges%#%
%!%2024-08-15%#%enjoying-the-outdoors%#%
%!%2024-07-02%#%walking-your-person%#%
%!%2024-07-02%#%the-cat-inspired-business%#%
%!%2024-07-02%#%seven-ways-to-get-a-fatter-tummy%#%
%!%2024-07-02%#%how-to-raise-successful-kittens%#%
%!%2024-07-02%#%controlling-the-litter-box%#%
%!%2024-06-26%#%seven-habits-of-highly-effective-cats%#%
%!%2024-05-23%#%are-you-a-fish-cat-or-a-chicken-cat%#%
%!%2024-05-22%#%why-do-dogs-exist%#%
%!%2023-07-02%#%customer-service-is-overrated%#%
%!%2023-03-05%#%catnip-in-history%#%
%!%2023-01-19%#%what-is-money%#%
%!%2023-01-11%#%catnip-how-to-tell-if-you-are-an-addict%#%
%!%2023-01-09%#%nappy-new-year%#%
The 'tag-story' map:
CATSTACK/data/maps/tag-story-map.txt ▾
philosophy%#%seven-habits-of-highly-effective-cats%#%
%!%philosophy%#%enjoying-the-outdoors%#%
%!%opinion%#%why-do-dogs-exist%#%
%!%opinion%#%walking-your-person%#%
%!%opinion%#%seven-habits-of-highly-effective-cats%#%
%!%opinion%#%how-to-raise-successful-kittens%#%
%!%opinion%#%enjoying-the-outdoors%#%
%!%opinion%#%customer-service-is-overrated%#%
%!%opinion%#%controlling-the-litter-box%#%
%!%health%#%enjoying-the-outdoors%#%
%!%health%#%catnip-how-to-tell-if-you-are-an-addict%#%
%!%education%#%why-do-dogs-exist%#%
%!%education%#%what-is-money%#%
%!%education%#%walking-your-person%#%
%!%education%#%seven-habits-of-highly-effective-cats%#%
%!%education%#%how-to-raise-successful-kittens%#%
%!%education%#%enjoying-the-outdoors%#%
%!%education%#%catnip-in-history%#%
%!%opinion%#%overcoming-tolerance%#%
%!%health%#%seven-ways-to-get-a-fatter-tummy%#%
%!%opinion%#%seven-ways-to-get-a-fatter-tummy%#%
%!%opinion%#%extreme-challenges%#%
Section 3: Accessing Records and Maps
The 'functions' file is the database management system. This file contains code for reading and writing the records and arrays, and querying the database.CATSTACK/inc/functions.php ▾
<?php
function createRecordId ($name) {
$newname = "";
if ($name !== "") {
$newname = trim ($name);
$newname = str_replace (" " , "-", $newname);
$newname = strtolower ($newname);
$newname = preg_replace('/[^A-Za-z0-9-]/', '', $newname);
$newname = preg_replace('/-+/', '-', $newname);
}
return $newname;
}
function initializeRecord ($keys){
$record = array ();
foreach ($keys as $Id => $key) {
$record[$key] = "";
}
return ($record);
}
function readDatabaseRecord ($keys, $filename) {
global $dl1;
$string = '';
if (file_exists($filename)) {
$string = file_get_contents ($filename);
}
$record = array();
$fArray1= explode ($dl1, $string);
foreach ($keys as $Id => $key) {
$record[$key] = "";
if (array_key_exists ($Id, $fArray1)) {
$record [$key] = $fArray1[$Id];
}
}
return $record;
}
function writeDatabaseRecord ($record, $filename) {
global $dl1;
$String = implode ($dl1, $record);
//file_put_contents ($filename, $String);
}
// Maps for table relationships
function addMapEntry ($map, $key1, $key2) {
global $dl1, $dl2;
$fArray1 = readArray ($map, $dl1);
$newentry = $key1 . $dl2 . $key2 . $dl2 . "\n";
array_push ($fArray1, $newentry);
$fArray1 = array_unique ($fArray1);
writeArray ($map, $fArray1, $dl1);
}
function addMapEntryReverse ($map, $key1, $key2) {
global $dl1, $dl2;
$fArray1 = readArray ($map, $dl1);
$newentry = $key1 . $dl2 . $key2 . $dl2 . "\n";
array_push ($fArray1, $newentry);
$fArray1 = array_unique ($fArray1);
rsort ($fArray1);
writeArray ($map, $fArray1, $dl1);
}
function removeMapEntries ($map, $key0, $key1) {
//Remove entries containing either or both key0 and key1
global $dl1, $dl2;
$fArray1 = readArray ($map, $dl1);
foreach ($fArray1 as $Id => $Item1) {
$fArray2 = explode ($dl2, $Item1);
if (array_key_exists (0, $fArray2) && array_key_exists (1, $fArray2)) {
if ($key0 !== "" && $key1 !== "") {
if ( $fArray2[0] === $key0 && $fArray2[1] === $key1 ) {
unset ($fArray1 [$Id]);
}
}
else if ($key0 === "" && $key1 !== "") {
if ($fArray2[1] === $key1) {
unset ($fArray1 [$Id]);
}
}
else if ($key0 !== "" && $key1 === "") {
if ($fArray2[0] === $key0) {
unset ($fArray1 [$Id]);
}
}
}
}
writeArray ($map, $fArray1, $dl1);
}
function selectMapEntries ($map, $key0, $key1) {
global $dl1, $dl2;
$fArray1 = readArray ($map, $dl1);
//returns an array with selected key
global $dl1, $dl2;
$selectedarray = array();
foreach ($fArray1 as $Item1) {
$fArray2 = explode ($dl2, $Item1);
if (array_key_exists (1, $fArray2)) {
if ($key0 && !$key1 ) {
if ($fArray2[0] == $key0 ){
array_push ($selectedarray, $fArray2[1]);
}
}
else if (!$key0 && $key1) {
if ($fArray2[1] === $key1) {
array_push ($selectedarray, $fArray2[0]);
}
}
}
}
return $selectedarray;
}
function selectMapKey ($map, $key0, $key1) {
//returns an single value
global $dl1, $dl2;
$returnvalue = '';
$fArray1 = readArray ($map, $dl1);
foreach ($fArray1 as $Id => $Item1) {
$fArray2 = explode ($dl2, $Item1);
if ( array_key_exists (1, $fArray2)) {
if (!$key0 && $key1) {
if ($fArray2[1] === $key1) {
$returnvalue = $fArray2[0];
break;
}
}
else if ($key0 && ! $key1) {
if ($fArray2[0] === $key0){
$returnvalue = $fArray2[1];
break;
}
}
}
}
return $returnvalue;
}
function extractFromMap($map, $key) {
//returns a new array of either the the first or second columns
global $dl1, $dl2;
$selectedarray = array();
$fArray1 = readArray ($map, $dl1);
foreach ($fArray1 as $Item1) {
$fArray2 = explode ($dl2, $Item1);
if ($key == 0) {
array_push ($selectedarray, $fArray2[0]);
}
else if ($key == 1) {
if (array_key_exists (1, $fArray2)) {
array_push ($selectedarray, $fArray2[1]);
}
}
}
return $selectedarray;
}
function moveToTrash ($table, $recordid) {
$oldfilename = 'data/' . $table . '/' . $recordid . '.txt';
$newfilename = 'data/trash/' . $table . '----' . $recordid . '.txt';
if (file_exists ($oldfilename)) {
rename ($oldfilename, $newfilename);
}
}
//ARRAYS
function readArray ($filename, $delimiter){
$fArray1 = array();
if (file_exists($filename)) {
$String = file_get_contents ($filename);
if ($String !== "") {
$fArray1 = explode ($delimiter, $String);
}
}
return $fArray1;
}
function writeArray ($filename, $array, $delimiter){
$String = implode ($delimiter, $array);
//file_put_contents ($filename, $String);
}
function addNameToArray ($filename, $name, $delimiter) {
if (file_exists($filename)) {
$String = file_get_contents ($filename);
$fArray1 = explode ($delimiter, $String);
array_push ($fArray1, $name);
$fArray1 = array_unique ($fArray1);
$String = implode ($delimiter, $fArray1);
$String = preg_replace('/,+/', ',', $String);
//file_put_contents ($filename, $String);
}
}
function removeNameFromArray ($filename, $name, $delimiter) {
if (file_exists($filename)) {
$String = file_get_contents ($filename);
$Array = explode ($delimiter, $String);
foreach ($Array as $Id => $Item) {
$Item = trim ($Item);
if ($Item === $name) {
unset ($Array [$Id]);
}
}
array_values ($Array);
$String = implode ($delimiter, $Array);
//file_put_contents ($filename, $String);
}
}
//Validate 'GET' value
function getFromQueryString ($label) {
$value = "";
if (isset ($_GET[$label])) {
$value = filter_var($_GET[$label], FILTER_SANITIZE_STRING) ;
$value = trim ($value);
}
return $value;
}
//Filter input text
function sanitizeFormInput($text) {
global $dl1, $dl2;
$text = trim($text);
$text = str_replace ($dl1, '', $text);
$text = str_replace ($dl2, '', $text);
return $text;
}
function showWords ($text) {
$fancytext = ucwords (str_replace ('-', ' ', $text));
return $fancytext;
}
//CHECK FOR DUPLICATE EMAILS
function checkForDuplicateEmail ($sendtoemail, $message) {
global $dl1, $dl2;
$error = false;
$emailarchive = readArray ('data/email-archive.txt', $dl1);
$emailentry = date ("Y-m-d") . $dl2 .$sendtoemail . $dl2 . $message . "\n";
if ( in_array ($emailentry, $emailarchive)) {
$error = true;
echo "<div class = 'error'>Message is a duplicate</div>";
}
return $error;
}
function randomString () {
$String = "";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for ($i = 0; $i < 7; $i++) {
$String .= $chars[rand(0, $size - 1)];
}
return $String;
}
function assignPostValuesToRecord ($postarray, $keys) {
//Assign values to record
$record = array();
foreach ($keys as $Id => $key) {
$record[$key] = "";
if (isset ($postarray[$key])) {
$record[$key] = sanitizeFormInput ($postarray[$key]);
}
}
return $record;
}
function saveToLog ($text) {
global $dl1, $dl2;
$currenttime = date ("h-i:sa");
$date = date ("Y-m-d");
$filename = 'data/log.txt';
$String = file_get_contents ($filename);
$String = $String . "\n\n " . $date . " " . $currenttime . " ". $text;
//file_put_contents ($filename, $String);
}
?>
For example, to find all the stories by an author, you would use the 'selectMapEntries' function and specify the 'story-author' map and the author record id. By leaving the story record variable emtpy, all the stories by the author will be returned in an array.
The home page queries the database using 2 maps - the date-story map, the story-author map and the tag-story map:
CATSTACK/pages/home.php ▾
<div class = 'content-column'>
<?php
echo "<h1>Latest Stories </h1>";
$dates = extractFromMap ('data/maps/date-story-map.txt', 0);
$stories = extractFromMap ('data/maps/date-story-map.txt', 1);
foreach ($dates as $id => $date) {
if (array_key_exists ($id, $stories)) {
$storyid = $stories[$id] ;
echo "<div class = 'gridcolumn'>";
$storyrecord = readDatabaseRecord ($storyrecordkeys, 'data/stories/' . $storyid . '.txt');
if ($storyrecord['image']) {
echo "<img src = 'data/images/" . $storyrecord['image'] . "' alt = '" . $storyrecord['title'] . "' >";
}
echo "<br><a href = 'index.php?page=display-story&story=" . $storyid . "'><h3>" . $storyrecord['title'] . "</h3></a>";
$authorid = $storyrecord['author'] ;
$authorrecord = readDatabaseRecord ($authorrecordkeys, 'data/authors/' . $authorid . '.txt' ) ;
echo "<h5>" . $storyrecord['date'] . "</h5>";
echo "<h5>" . $authorrecord['name'] . "</h5>";
echo "</div>";
}
}
?>
</div><div class = 'sidebar-column'>
<?php
echo "<h2>Authors</h2>";
$authors = extractFromMap ('data/maps/story-author-map.txt', 1);
$authors = array_unique ($authors);
foreach ($authors as $authorid) {
$authorrecord = readDatabaseRecord ($authorrecordkeys, 'data/authors/' . $authorid . '.txt' );
echo "<a href = 'index.php?page=display-author&author=" . $authorid . "'>";
echo "<b>" . $authorrecord['name'] ."</b><br>";
echo "</a>";
}
echo "<h2>Tags</h2>";
$tagarray = readArray ('data/tags.txt', ',');
foreach ($tagarray as $tag) {
echo "<a href = 'index.php?page=display-tag&tag=" . $tag . "'><b>" . showWords ( $tag) ."</b></a><br>";
}
?>
</div>
The 'display-tag' page queries the database using the tag-story map:
CATSTACK/pages/display-tag.php ▾
<h1>Stories for Tag</h1>
<?php
$tag = getFromQueryString ('tag');
echo "<h2>" . showWords ($tag) . "</h2>";
$currentarray = selectMapEntries ('data/maps/tag-story-map.txt', $tag, "");
$tagarray = readArray ('data/tags.txt', ',');
$array1 = scandir ('data/stories');
foreach ($array1 as $item1) {
if (substr ($item1, 0, 1) !== '.') {
$storyid = str_replace ('.txt', '', $item1);
$stories = selectMapEntries ('data/tag-story-map.txt', '', $storyid);
if (in_array($storyid, $currentarray)) {
echo "<a href = 'index.php?page=display-story&story=" . $storyid . "'>" . showWords ($storyid) . "</a><br>";
}
}
}
?>