Skip to main content

Add Row Function

The add_row function allows you to append new data to an existing database without overwriting previous records. Unlike put, which replaces the entire database, add_row ensures that old data remains intact while adding new entries.


How to Use the add_row Function

Basic Usage

To add a new record to the database:

$newUser = [
"username" => "alice",
"email" => "alice@example.com"
];

$sdb->add_row("users", $newUser);

This appends alice to the users.sdb database without deleting any previous records.


How the add_row Function Works

  1. Retrieves Existing Data

    • Calls get($file) to fetch current database contents.
    • If the database is empty, it initializes a new array.
  2. Appends the New Entry

    • Adds the new record to the existing data.
  3. Encodes & Saves the Updated Database

    • Converts the updated dataset into JSON format.
    • Calls put($file, $final), replacing the database with the updated data.

Return Behavior

  • Success → The new row is added to the database.
  • Failure → If put fails, data is not updated.

Example: Adding Multiple Users

You can use add_row multiple times to keep appending records:

$sdb->add_row("users", ["username" => "bob", "email" => "bob@example.com"]);
$sdb->add_row("users", ["username" => "charlie", "email" => "charlie@example.com"]);

This keeps adding new users without erasing the existing ones.


⚠️ Important Notes

Use add_row when:

  • You want to expand the database without losing previous records.
  • Storing multiple entries (e.g., a user list, logs, inventory).

Do NOT use add_row when:

  • You need to update existing records (use an update function instead).
  • The database is not structured as an array.
  • Performance is a concern (if you are expecting heavy performance, SwartzDB is not the right choice).

Final Thoughts

The add_row function is a safe and non-destructive way to grow your SwartzDB database.
Use it whenever you need to add new entries without risking data loss.