Database-less Approach to Store Some Data in PHP

806 Views Asked by At

I am new to PHP but not programming in general. I want to store some data I retrieve from the web service but I do not think I want a database for that. First, data will be updated quite frequently and its size is always less than 1MB. What is the best, fast but efficient approach in PHP on Apache? Note: I am using a hosting provider so I do not prefer custom installations. Perhaps, singleton? Thanks

7

There are 7 best solutions below

0
On BEST ANSWER

Use a database. Otherwise you are stuck serialising a file. But to do this right you need to implement concurrency controls.

Save yourself the time and energy and use a database.

0
On

Try using a flat file. If you don't need to do any sort of fancy lookups, that is.

0
On

The obvious alternative to the database is file storage. PHP can read and write good old disk files; see fopen(), fread(), fwrite() and then some. You'll need to designate a folder on the server (aside from the public_html space) for file(s) and come up with a naming scheme and data format.

0
On

I think the question becomes, how long will the data be stored for? If you are storing the data until it is replaced or longer than a single user session, personally I believe a database is the ideal solution - it is designed to be very efficient with quickly altering and retrieving data.

If the data is only kept for a single user session, you could use PHP sessions to store the data as an array.

The other alternative is to store the data in a file. However, this can be much less efficient in retrieving small amounts of data.

0
On

You could use a Cloud service (Amazon, Google ...). But apart from making your app more complecated and brittle and yourself more hip I don't see any benefit over using a normal db or a flat file.

0
On

You could save arrays in a plain text file, with serialize.

Something like

$fh = fopen("db.txt", "w");
fwrite($fh, serialize(array("field"=>"data"));
fclose($fh);

Retrieve it again with fread and mode "r" and then the method unserialize.

$fh = fopen("db.txt", "r");
$data = unserialize(fread($fh));
fclose($fh);

And then manage your data in the array.

0
On

You can store your data in xml files and use an simplexml to load the data an manage it, like:

$xml = simplexml_load_file("test.xml");

Then you can have a list of the nodes you defined and do your stuff. For further reference you can check out the following:

SimpleXML tutorial