Skip to main content

Put Function

The put function in SwartzDB is used to store data in the database. It takes the input, encrypts it for security, and writes it to the specified .sdb file.

WARNING: Using put will replace the entire database!
  • It is recommended to use put only when initializing an empty database.
  • If you need to update data without deleting existing entries, use Add Row or Update Row functions

How to Use the put Function

Basic Usage

To store data in a new database:

$data = [
"username" => "john_doe",
"email" => "john@example.com",
"role" => "admin"
];

$sdb->put("users", json_encode($data));

This will overwrite any existing users.sdb file with the new data.

Using put with Error Reporting

To enable error logging [to browser console], pass true as the third argument:

$sdb->put("users", json_encode($data), true);

This logs any write failures for debugging.


How the put Function Works

  1. Encrypts the Data

    • Uses double encryption ($key, $Ekey) to protect stored information.
    • Ensures data security before writing to disk.
  2. Writes to File

    • Saves the encrypted data to the .sdb file using the safeWrite method.
    • Ensures data is securely stored.
  3. Error Handling

    • If writing fails, an error is logged (if enabled).
    • Exceptions are caught and reported.

Return Values

  • Success → Data is securely written to the database.
  • Failure → Logs an error if the file cannot be written.

Example: Storing Multiple Entries

Since put overwrites the database, store data in an array format to avoid data loss:

$users = [
["username" => "john_doe", "email" => "john@example.com"],
["username" => "jane_doe", "email" => "jane@example.com"]
];

$sdb->put("users", json_encode($users));

When to Use put (and When Not To)

Use put when:

  • Creating a new database for the first time.
  • Replacing existing data with a fresh dataset.
  • Resetting a database to an initial state.

Do NOT use put when:

  • You want to update or append data (it will erase old data).
  • You need to keep a history of changes.
  • The database contains important existing records.

Safer Alternatives

If you need to modify a database without overwriting everything, consider:

  • Appending new data using the add row function.
  • Updating records selectively using the update row function.

Final Thoughts

The put function is a powerful but destructive tool in SwartzDB.
Use it wisely—only when you are certain that replacing all data is the right approach.