attempt_truncate()

public function attempt_truncate(string $table, bool $validate_table = true): bool

Description

Attempts to truncate a table but only if it's empty. If the table contains rows, the method returns false and does nothing. This is a safety feature to prevent accidental data loss. The method can optionally validate that the table exists before attempting the operation.

Parameters

Parameter Type Description Default Required
table string The name of the table to attempt truncation on. - Yes
validate_table bool If true, validates that the table exists before checking row count. If false, skips table validation (use only when certain table exists). true No

Return Value

Type Description
bool True if truncate was performed (table was empty), false if table had rows (no truncation occurred).

Exceptions

  • RuntimeException - If the specified table does not exist (when $validate_table is true).

Example #1: Basic Safe Truncation

The code sample below demonstrates how to safely attempt to truncate a table, ensuring no data loss.

PHP
// Only truncate if the table is empty
if ($this->db->attempt_truncate('temp_sessions')) {
    echo "Table 'temp_sessions' was empty and has been truncated.";
} else {
    echo "Table 'temp_sessions' contains data; truncation was not performed.";
}

Example #2: Truncate with Table Validation Disabled

The code sample below demonstrates how to skip table existence validation when you're certain the table exists.

PHP
// Skip validation if you're certain the table exists
$result = $this->db->attempt_truncate('sessions', false);
if ($result) {
    echo "Sessions table was empty and has been truncated.";
}

Example #3: Conditional Table Cleanup

The code sample below demonstrates how to use attempt_truncate() in a maintenance script.

PHP
$tables_to_clean = ['cache_data', 'temp_uploads', 'session_backups'];

foreach ($tables_to_clean as $table) {
    if ($this->db->table_exists($table)) {
        $truncated = $this->db->attempt_truncate($table);
        if ($truncated) {
            echo "Table '$table' was empty and truncated.";
        } else {
            echo "Table '$table' contains data; preserved.";
        }
    }
}

Important Notes

  • The $table parameter is required.
  • The $validate_table parameter defaults to true for safety.
  • Uses TRUNCATE TABLE SQL command which resets auto‑increment counters.
  • Unlike DELETE FROM table, truncate cannot be rolled back in some database configurations.
  • This method is safer than direct truncation because it checks row count first.
  • If debug mode is enabled, the generated SQL query will be displayed before execution.
  • Useful for:
    1. Maintenance scripts that clean temporary tables
    2. Resetting test data without risking production data loss
    3. Safe table initialization in installation routines