Skip to main content

Get Function

SwartzDB provides the get function to fetch stored data from the database. Since SwartzDB stores data in encrypted JSON format, the get function automatically decrypts and decodes the data before returning it.


How to Use the get Function

Basic Data Retrieval

To retrieve all data from a database file, use:

$data = $sdb->get("mydatabase");

This will return the data in an array format, making it easy to manipulate.

Reverse Data Order

If you want the data in reverse order, use:

$data = $sdb->get("mydatabase", "reverse");

This is useful for fetching recent entries first (e.g., latest logs or messages).


How the get Function Works

  1. Retrieves the Encrypted File Contents

    • Reads data from the specified .sdb file.
    • If the file does not exist or is unreadable, it returns null.
  2. Decryption Process

    • The function decrypts the data twice using global encryption keys ($cipher, $key, $Ekey, $iv).
    • If decryption fails, the data remains inaccessible.
  3. JSON Decoding

    • Converts the decrypted JSON string into an associative array.
    • If the database is empty, it returns an empty array.
  4. Sorting (Optional)

    • If "reverse" is passed as the second parameter, it reverses the array order before returning.

Return Values

  • Array → Successfully retrieved data.
  • Empty Array ([]) → Database exists but has no stored data.
  • null → Error occurred (e.g., file missing, decryption failure).

Example: Handling Retrieved Data

Since the function returns an associative array, you can loop through it easily:

$users = $sdb->get("users");

if (!empty($users)) {
foreach ($users as $user) {
echo "Username: " . $user["username"] . "<br>";
}
} else {
echo "No users found.";
}

Error Handling

Enable error reporting by passing true as the third argument:

$data = $sdb->get("mydatabase", "", true);

This ensures errors (like unreadable files) are logged [in the browser console] for debugging.


Use Cases for get

  • Fetching all users, logs, or records stored in SwartzDB.
  • Displaying data in reverse order (e.g., latest transactions first).
  • Checking if a database is empty before inserting new entries.

Important Notes

  • Empty Data return an empty array, not null.
  • Data is automatically formatted for easier processing.

Using the get function, you can safely retrieve encrypted data, ensuring both security and accessibility.