Many websites use databases for storing data for use by web applications. There are situations in which this is not the best solution, however. For light, moderate, or temporary storage requirements, you might prefer to use flat files, session variables, and cookies. This article will describe how to create a class that handle all of these. It is the first of two parts.
Our datastore class wouldn't be much good if we couldn't store anything in it, so that is the next thing to get into. The first method up is the add_new_item method.
function add_new_item($arr,$id) { if(isarray($arr)) { $keys = array_keys($arr); for($i= 0;$i < count($arr);$i++) { $this->items[$id][$keys[$i]] = $arr[$keys[$i]]; $this->edited = true; } } else [ $this->err("First argument must be an array",1); ] }
This method accepts two arguments. The first is an associative array to serve as a row of records, and the second is a unique id to act as a key. It adds this array to the items array. If you are wondering why a loop is used, this is for future expansion of the method to allow processing of each element as it is set in the items array.
One suggestion for using this method is for storing html form field values directly. By using the versatile array functions provided by PHP you could process $_POST or $_GET array values and then store them directly into datastore with very little code. This is especially useful for multi-page forms that are processed once all the data is collected.
You also may have been wondering what the "err" method is. This is a method of datastore that will store the most recent error to allow easier debugging. The first argument is the error message and the second allows the method to both set and get error messages. If it is absent the method returns the current error.There is no error suppression in this datastore code, so once you have a good idea how to use it that may be something to include. You can then let the err method do the work of alerting you when something goes wrong.
Arguments are the key of the item to alter, the data to store and an optional specific field to store the data in. If no field is specified then the second argument should be an associative array (data row) to replace the row specified. If a field is specified then the second argument should be the value you wish to store in that field.