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.
put will replace the entire database!- It is recommended to use
putonly 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
-
Encrypts the Data
- Uses double encryption (
$key,$Ekey) to protect stored information. - Ensures data security before writing to disk.
- Uses double encryption (
-
Writes to File
- Saves the encrypted data to the
.sdbfile using thesafeWritemethod. - Ensures data is securely stored.
- Saves the encrypted data to the
-
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));
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 rowfunction. - Updating records selectively using the
update rowfunction.
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.