Code Igniter User Guide Version 1.5.0


Database Utility Class

The Database Utility Class contains functions that help you manage your database.

Table of Contents

Initializing the Utility Class

Important:  This class must be initialized independently since it is a separate class from the main Database class. More info below...

To initialize this class please use the following code:

$this->load->dbutil()

You can also autoload this class from within your config/autoload.php file by specifying dbutil in the $autoload['libraries'] array.

Once initialized you will access the functions using the $this->dbutil object:

$this->dbutil->some_function()

$this->dbutil->create_database('db_name')

Permits you to create a database using the name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

if ($this->dbutil->create_database('my_db'))
{
    echo 'Database created!';
}

$this->dbutil->drop_database('table_name')

Permits you to drop a database using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

if ($this->dbutil->drop_database('my_db'))
{
    echo 'Database deleted!';
}

$this->dbutil->list_databases()

Returns an array of database names:

$dbs = $this->dbutil->list_databases();

foreach($dbs as $db)
{
    echo $db;
}

$this->dbutil->optimize_table('table_name');

Permits you to optimize a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

if ($this->dbutil->optimize_table('table_name'))
{
    echo 'Success!'
}

Note: Not all database platforms support table optimization.

$this->dbutil->repair_table('table_name');

Permits you to repair a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

if ($this->dbutil->optimize_table('table_name'))
{
    echo 'Success!'
}

Note: Not all database platforms support table repairs.

$this->dbutil->optimize_database();

Permits you to optimize the database your DB class is currently connected to. Returns an array containing the returned status messages or FALSE on failure.

$result = $this->dbutil->optimize_databass();

if ($result !== FALSE)
{
    print_r($result);
}

Note: Not all database platforms support table optimization.

$this->dbutil->csv_from_result($db_result)

Permits you to generate a CSV file from a query result. The first parameter of the function must contain the result object from your query. Example:

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

echo $this->dbutil->csv_from_result($query);

The second and third parameters allows you to set the delimiter and newline character. By default tabs are used as the delimiter and "\n" is used as a new line. Example: $delimiter = ",";
$newline = "\r\n";

echo $this->dbutil->csv_from_result($query, $delimiter, $newline);

Important:  This function will NOT write the CSV file for you. It simply creates the CSV layout. If you need to write the file use the File Helper.

$this->dbutil->xml_from_result($db_result)

Permits you to generate an XML file from a query result. The first parameter expects a query result object, the second may contain an optional array of config parameters. Example:

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

$config = array (
                  'root'    => 'root',
                  'element' => 'element',
                  'newline' => "\n",
                  ';tab'    => "\t"
                );

echo $this->dbutil->xml_from_result($query, $config);

Important:  This function will NOT write the XML file for you. It simply creates the XML layout. If you need to write the file use the File Helper.

$this->dbutil->backup()

Permits you to backup your full database or individual tables. The backup data can be compressed in either Zip or Gzip format, and it can be downloaded to your desktop, archived to your server, returned as a string, or simply displayed.

Note: Due to the limited execution time and memory available to PHP, backing up very large databases may not be possible. If your database is very large you might need to backup directly from your SQL server via the command line, or have your server admin do it for you if you do not have root privileges.

Usage example:

$this->dbutil->backup();

// When no parameters are passed the full database is backed up and downloaded to your desktop as a Gzip file.

Setting Backup Preferences

Preferences are set by submitting an array of values to the first parameter of the backup function. Example:

$prefs = array(
                'tables'      => array('table1', 'table2'),  // Array of tables to backup.
                'ignore'      => array(),             // List of tables to omit from the backup
                'format'      => 'txt',               // gzip, zip, txt
                'action'      => 'archive',           // download, archive, echo, return
                'filename'    => 'sql_archive',       // File name - no file extension!
                'filepath'    => '/path/to/folder/',  // Path needed only when archiving to your server
                'add_drop'    => TRUE,                // Whether to add DROP TABLE statements to backup file
                'add_insert'  => TRUE,                // Whether to add INSERT data to backup file
                'newline'     => "\n"                 // Newline character used in backup file
              );

$this->dbutil->backup($prefs);

Description of Backup Preferences

Preference Default Value Options Description
tablesempty arrayNoneAn array of tables you would liked backed up. If left blank all tables will be exported.
ignoreempty arrayNoneAn array of tables you would liked the backup routine to ignore.
formatgzipgzip, zip, txtThe file format of the export file.
actiondownloaddownload, archive, echo, returnWhat action you would like applied to the data. "download" sends it to your desktop, "archive" writes the file to your server, "return" returns the backup as a string, and "echo" simply echos it out for viewing.
filenamethe current date/timeNoneThe name of the export file. DO NOT include the file extension.
filepathempty stringNoneThe path to the directory where you would like the archived file written to. Used ONLY when the "archive" action is set.
add_dropTRUETRUE/FALSEWhether to include DROP TABLE statements in your SQL export file.
add_insert/strong>TRUETRUE/FALSEWhether to include INSERT statements in your SQL export file.
newline/strong>"\n""\n", "\r", "\r\n"Type of newline to use in your SQL export file.