Add Function
The add function in SwartzDB is used to append multiple rows of data to a file without removing existing records. Unlike put, which overwrites the file, add ensures that new data is merged into the existing dataset.
How add Works
- Retrieves the current data from the file.
- Accepts multiple new rows as separate parameters or a single array.
- Merges the new data with the existing data.
- Saves the updated dataset back to the file.
Example Usage
Adding a Single Entry
$sdb->add("users", ["name" => "John", "age" => 30]);
- Fetches data from
users. - Adds
{"name": "John", "age": 30}to it. - Saves the updated JSON file.
Adding Multiple Entries
The function allows adding multiple rows in a single call:
$sdb->add("users",
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 28]
);
This appends both rows to users.
Adding an Array of Data
Instead of passing multiple arguments, you can pass an array:
$newUsers = [
["name" => "Charlie", "age" => 35],
["name" => "Diana", "age" => 22]
];
$sdb->add("users", $newUsers);
This approach is useful when handling bulk inserts dynamically.
Why Use add?
✅ Prevents Data Loss – Unlike put, it doesn’t overwrite existing data.
✅ Supports Bulk Inserts – Accepts multiple rows in a single function call.
✅ Flexible Input – Works with individual entries and arrays.
Conclusion
The add function is ideal for appending multiple records in SwartzDB while preserving the existing dataset. It's a simple way to grow your data without worrying about overwriting.