Package: Zebra_Database

Class: Zebra_Database

source file: /Zebra_Database.php

Class Overview


An advanced, compact, lightweight, object-oriented MySQL database wrapper, built upon PHP's MySQLi extension. It provides methods for interacting with MySQL databases that are more powerful and intuitive than PHP's default ones.

It supports transactions and provides ways for caching query results either by saving cached data on the disk, or by using memcache.

Provides a comprehensive debugging interface with detailed information about the executed queries: execution time, returned/affected rows, excerpts of the found rows, error messages, etc. It also automatically EXPLAIN's each SELECT query (so you don't miss those keys again!).

It encourages developers to write maintainable code and provides a better default security layer by encouraging the use of prepared statements, where arguments are escaped automatically.

The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to E_ALL.

Visit http://stefangabos.ro/php-libraries/zebra-database/ for more information.

For more resources visit http://stefangabos.ro/

Author(s):

Version:

  • 2.8 (last revision: March 15, 2013)

Copyright:

  • (c) 2006 - 2013 Stefan Gabos

Class properties

integer $affected_rows

After an INSERT, UPDATE or DELETE query, read this property to get the number of affected rows.

This is a read-only property!

  1. // after an "action" query...
  2. echo $db->affected_rows;
Top

string $cache_path

Path (with trailing slash) where to store cached queries results.

The path must be relative to your working path and not the class' path!

Top

string $caching_method

The method to use for caching query results.

Can be either

  • disk - query results are cached as files on the disk, at the path specified by cache_path.
  • memcache - query results are cached using a memcache server; when using this method, make sure to also set the appropriate values for memcache_host, memcache_port and, optionally, memcache_compressed.
    For using memcache as caching method, PHP version must be 4.3.3+, must be compiled with the memcache extension and, if memcache_compressed property is set to TRUE, needs to be configured with--with-zlib[=DIR].
If caching method is set to "memcache", memcache_host, memcache_port and, optionally memcache_compressed, must be set *prior* to calling the connect() method! Failing to do so will disable caching.

  1. // the host where memcache is listening for connections
  2. $db->memcache_host 'localhost';
  3.  
  4. // the port where memcache is listening for connections
  5. $db->memcache_port 11211;
  6.  
  7. // for this to work, php needs to be configured with --with-zlib[=dir] !
  8. // set it to FALSE otherwise
  9. $db->memcache_compressed true;
  10.  
  11. // cache queries using the memcache server
  12. $db->caching_method 'memcache';
  13.  
  14. // only after we've set up everything it is time to connect
  15. $db->connect(...)

Caching is done on a per-query basis, by setting the "cache" argument when calling some of the library's methods like query(), select(), dcount(), dlookup(), dmax() and dsum()!

Default is 'disk'.

Tags:
since: 2.7
Top

integer $console_show_records

Sets how many of the records returned by a SELECT query should be shown in the debug console.

  1. // show more records

Be aware that having this property set to a high number (thousands or more) and having a query that returns that many rows, can cause your script to crash due to memory limitations. In this case you should either lower the value of this property or try and set PHP's memory limit higher using:

  1. // set PHP's memory limit to 20 MB
  2. ini_set('memory_limit','20M');

Default is 20.

Tags:
since: 1.0.9
Top

boolean $debug

Setting this property to TRUE, will instruct the class to generate debug information for each query it executes.

Debug information can later be reviewed by calling the show_debug_console() method.

Don't forget to set this to FALSE when going live. Generating the debug information consumes a lot of resources and is meant to be used in the development process only!.

Note that not calling show_debug_console() when debug is set to TRUE, will not disable debug information: debug information will still be generated only it will not be shown!

The propper solution is to always use show_debug_console() at the end of your scripts and simply change the state of $debug as show_debug_console() will not display anything if $debug is set to FALSE.

  1. $db->debug false;

Default is TRUE.

Top

array $debugger_ip

An array of IP addresses for which to show the debug console (when calling show_debug_console() and debug is TRUE).

Leaving this an empty array, will display the debug console for everybody.

  1. // show the debug console only to specific IPs
  2. $db->debugger_ip array('192.168.0.12''192.168.0.13');

Default is an empty array.

Tags:
since: 1.0.6
Top

boolean $disable_warnings

By default, if set_charset() is not called, a warning message will be displayed in the debug console.

The ensure that data is both properly saved and retrieved from the database you should call this method, first thing after connecting to the database.

If you don't want to call the method and don't want to see the warning either, set this property to FALSE.

Default is TRUE.

Top

integer $found_rows

After a SELECT query done through either select() or query() methods, and having set the $calc_rows argument to TRUE, this property would contain the number of records that would have been returned if there was no LIMIT applied to the query.

If $calc_rows is FALSE, or is TRUE but there is no LIMIT applied to the query, this property's value will be equal to returned_rows.

This is a read-only property!

Top

boolean $halt_on_errors

By setting this property to TRUE, the execution of the script will be halted upon an unsuccessful query and the debug console will be displayed, if debug is TRUE and the viewer's IP address is in the debugger_ip array (or $debugger_ip is an empty array).

  1. // don't stop execution on critical errors (if possible)
  2. $db->halt_on_errors false;

Default is TRUE.

Tags:
since: 1.0.5
Top

string $log_path

Path (with trailing slash) where to store the log file.

The path is relative to your working directory.

Data is written to the log file when calling the write_log() method.

At the given path the script will attempt to create a file named "log.txt". Remember to grant the appropriate rights to the script!

IF YOU'RE LOGGING, MAKE SURE YOU HAVE A CRON JOB OR ANYTHING THAT DELETES THE LOG FILE FROM TIME TO TIME!

Remember that the library will try to write errors to the system log (if PHP is configured so) only when the debug property is set to FALSE (as when the debug property is set to TRUE the error messages are reported in the debug console);

Top

integer $max_query_time

Time (in seconds) after which a query will be considered as running for too long.

If a query's execution time exceeds this number, a notification email will be automatically sent to the address defined by notification_address, having notifier_domain in subject.

  1. // consider queries running for more than 5 seconds as slow and send email
  2. $db->max_query_time 5;

Default is 10.

Top

boolean $memcache_compressed

Setting this property to TRUE will instruct to library to compressed (using zlib) the cached results.

For this to work, PHP needs to be configured with --with-zlib[=DIR] !

Set this property only if you are using "memcache" as caching_method.

Default is FALSE.

Tags:
since: 2.7
Top

mixed $memcache_host

The host where memcache is listening for connections.

Set this property only if you are using "memcache" as caching_method.

Default is FALSE.

Tags:
since: 2.7
Top

mixed $memcache_port

The port where memcache is listening for connections.

Set this property only if you are using "memcache" as caching_method.

Default is FALSE.

Tags:
since: 2.7
Top

boolean $minimize_console

By setting this property to TRUE, a minimized version of the debug console will be shown by default.

Clicking on it, will show the full debug console.

Default is TRUE

Tags:
since: 1.0.4
Top

string $notification_address

Email address to which notification emails to be sent when a query's execution time exceeds the number of seconds set by max_query_time.

If a query's execution time exceeds the number of seconds set by max_query_time, a notification email will be automatically sent to the address defined by notification_address, having notifier_domain in subject.

  1. // the email address where to send an email when there are slow queries
  2. $db->notifier_address 'youremail@yourdomain.com';
Top

string $notifier_domain

Domain name to be used in the subject of notification emails sent when a query's execution time exceeds the number of seconds set by max_query_time.

If a query's execution time exceeds the number of seconds set by max_query_time, a notification email will be automatically sent to the address defined by notification_address, having notifier_domain in subject.

  1. // set a domain name so that you'll know where the email comes from
  2. $db->notifier_domain 'yourdomain.com';
Top

integer $returned_rows

After a SELECT query, read this property to get the number of returned rows.

This is a read-only property!

See found_rows also.

  1. // after a select query...
  2. echo $db->returned_rows;
Tags:
since: 1.0.4
Top

Class methods

constructor __construct()

Zebra_Database __construct ( )

Constructor of the class

Initializes the class' properties

Top

method close()

boolean close ( )

Closes the MySQL connection.

Tags:
return: Returns TRUE on success or FALSE on failure.
since: 1.1.0
Top

method connect()

void connect ( string $host , string $user , string $password , string $database , [ boolean $connect = false] )

Opens a connection to a MySQL Server and selects a database.

Since the library is using "lazy connection" (it is not actually connecting to the database until the first query is executed) there's no link identifier available when calling this method!

If you need the link identifier use the get_link() method!

If you need the connection to the database to be made right away, set the "connect" argument to TRUE.

  1. // create the database object
  2. $db new Zebra_Database();
  3.  
  4. // notice that we're not doing any error checking. errors will be shown in the debug console
  5. $db->connect('host''username''password''database');
  6.  
  7. //  code goes here
  8.  
  9. // show the debug console (if enabled)
Parameters:
string $host The address of the MySQL server to connect to (i.e. localhost).
string $user The user name used for authentication when connecting to the MySQL server.
string $password The password used for authentication when connecting to the MySQL server.
string $database The database to be selected after the connection is established.
boolean $connect

(Optional) Setting this argument to TRUE will force the library to connect to the database right away.

Default is FALSE.

Top

method dcount()

mixed dcount ( string $column , string $table , [ string $where = ''] , [ array $replacements = ''] , [ mixed $cache = false] , [ boolean $highlight = false] )

Counts the values in a column of a table.

  1. // count male users
  2. $male $db->dcount('id''users''gender = "M"');
  3.  
  4. // when working with variables you should use the following syntax
  5. // this way variables will be mysqli_real_escape_string-ed first
  6. $users $db->dcount('id''users''gender = ?'array($gender));
Tags:
return:

Returns the number of counted records, or FALSE if no records matching the given criteria (if any) were found. It also returns FALSE if there are no records in the table or on error.

This method may return boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0. Use the === operator for testing the return value of this method.

Parameters:
string $column Name of the column in which to do the counting.
string $table Name of the table containing the column.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method delete()

boolean delete ( string $table , [ string $where = ''] , [ array $replacements = ''] , [ boolean $highlight = false] )

Deletes rows from a table.

  1. // delete male users
  2. $db->delete('users''gender = "M"');
  3.  
  4. // when working with variables you should use the following syntax
  5. // this way variables will be mysqli_real_escape_string-ed first
  6. $db->delete('users''gender = ?'array($gender));
Tags:
return: Returns TRUE on success, or FALSE on error
since: 1.0.9
Parameters:
string $table Table from which to delete.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method dlookup()

mixed dlookup ( string $column , string $table , [ string $where = ''] , [ array $replacements = ''] , [ mixed $cache = false] , [ boolean $highlight = false] )

Returns one or more columns from ONE row of a table.

  1. // get name, surname and age of all male users
  2. $result $db->dlookup('name, surname, age''users''gender = "M"');
  3.  
  4. // when working with variables you should use the following syntax
  5. // this way variables will be mysqli_real_escape_string-ed first
  6. $result $db->dlookup('name, surname, age''users''gender = ?'array($gender));
Tags:
return: Found value/values, or FALSE if no records matching the given criteria (if any) were found. It also returns FALSE if there are no records in the table or on error.
Parameters:
string $column

One or more columns to return data from.

If only one column is specified, the returned result will be the specified column's value, whereas if more columns are specified, the returned result will be an associative array!

You may use "*" (without the quotes) to return all the columns from the row.

string $table Name of the in which to search.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method dmax()

mixed dmax ( string $column , string $table , [ string $where = ''] , [ array $replacements = ''] , [ mixed $cache = false] , [ boolean $highlight = false] )

Looks up the maximum value in a column of a table.

  1. // get the maximum age of male users
  2. $result $db->dmax('age''users''gender = "M"');
  3.  
  4. // when working with variables you should use the following syntax
  5. // this way variables will be mysqli_real_escape_string-ed first
  6. $result $db->dmax('age''users''gender = ?'array($gender));
Tags:
return:

The maximum value in the column, or FALSE if no records matching the given criteria (if any) were found. It also returns FALSE if there are no records in the table or on error.

This method may return boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0. Use the === operator for testing the return value of this method.

Parameters:
string $column Name of the column in which to search.
string $table Name of table in which to search.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method dsum()

mixed dsum ( string $column , string $table , [ string $where = ''] , [ array $replacements = ''] , [ mixed $cache = false] , [ boolean $highlight = false] )

Sums the values in a column of a table.

Example:

  1. // get the total logins of all male users
  2. $result $db->dsum('login_count''users''gender = "M"');
  3.  
  4. // when working with variables you should use the following syntax
  5. // this way variables will be mysqli_real_escape_string-ed first
  6. $result $db->dsum('login_count''users''gender = ?'array($gender));
Tags:
return:

Returns the sum, or FALSE if no records matching the given criteria (if any) were found. It also returns FALSE if there are no records in the table or on error.

This method may return boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0. Use the === operator for testing the return value of this method.

Parameters:
string $column Name of the column in which to sum values.
string $table Name of the table in which to search.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method escape()

string escape ( string $string )

Escapes special characters in a string for use in an SQL statement.

This method also encloses given string in single quotes!

Works even if magic_quotes is ON.

  1. // use the method in a query
  2. // THIS IS NOT THE RECOMMENDED METHOD!
  3. $db->query('
  4.     SELECT
  5.         *
  6.     FROM
  7.         users
  8.     WHERE
  9.         gender = "' $db->escape($gender'"
  10. ');
  11.  
  12. // the recommended method
  13. // (variable are automatically escaped this way)
  14. $db->query('
  15.     SELECT
  16.         *
  17.     FROM
  18.         users
  19.     WHERE
  20.         gender = ?
  21. 'array($gender));
Tags:
return: Returns the escaped string.
Parameters:
string $string String that is to be escaped.
Top

method fetch_assoc()

mixed fetch_assoc ( [ resource $resource = ''] )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. The data is taken from the resource created by the previous query or from the resource given as argument.

  1. // create the database object
  2. // run a query
  3. $db->query('SELECT * FROM table WHERE criteria = ?'array($criteria));
  4.  
  5. // iterate through the found records
  6. while ($row $db->fetch_assoc()) {
  7.  
  8.     // code goes here
  9.  
  10. }
Tags:
return: Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead, or FALSE if there are no more rows.
Parameters:
resource $resource

(Optional) Resource to fetch.

If not specified, the resource returned by the last run query is used.

Top

method fetch_assoc_all()

mixed fetch_assoc_all ( [ string $index = ''] , [ resource $resource = ''] )

Returns an associative array containing all the rows from the resource created by the previous query or from the resource given as argument and moves the internal pointer to the end.

  1. // run a query
  2. $db->query('SELECT * FROM table WHERE criteria = ?'array($criteria));
  3.  
  4. // fetch all the rows as an associative array
  5. $records $db->fetch_assoc_all();
Tags:
return: Returns an associative array containing all the rows from the resource created by the previous query or from the resource given as argument and moves the internal pointer to the end. Returns FALSE on error.
since: 1.1.2
Parameters:
string $index

(Optional) A column name from the records, containing unique values.

If specified, each entry in the returned array will have its index equal to the the value of the specified column for each particular row.

If not specified, returned array will have numerical indexes, starting from 0.

resource $resource

(Optional) Resource to fetch.

If not specified, the resource returned by the last run query is used.

Top

method fetch_obj()

mixed fetch_obj ( [ resource $resource = ''] )

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

The data is taken from the resource created by the previous query or from the resource given as argument.

  1. // run a query
  2. $db->query('SELECT * FROM table WHERE criteria = ?'array($criteria));
  3.  
  4. // iterate through the found records
  5. while ($row $db->fetch_obj()) {
  6.  
  7.     // code goes here
  8.  
  9. }
Tags:
return: Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead, or FALSE if there are no more rows.
since: 1.0.8
Parameters:
resource $resource

(Optional) Resource to fetch.

If not specified, the resource returned by the last run query is used.

Top

method fetch_obj_all()

mixed fetch_obj_all ( [ string $index = ''] , [ resource $resource = ''] )

Returns an associative array containing all the rows (as objects) from the resource created by the previous query or from the resource given as argument and moves the internal pointer to the end.

  1. // run a query
  2. $db->query('SELECT * FROM table WHERE criteria = ?'array($criteria));
  3.  
  4. // fetch all the rows as an associative array
  5. $records $db->fetch_obj_all();
Tags:
return: Returns an associative array containing all the rows (as objects) from the resource created by the previous query or from the resource given as argument and moves the internal pointer to the end. Returns FALSE on error.
since: 1.1.2
Parameters:
string $index

(Optional) A column name from the records, containing unique values.

If specified, each entry in the returned array will have its index equal to the the value of the specified column for each particular row.

If not specified, returned array will have numerical indexes, starting from 0.

resource $resource

(Optional) Resource to fetch.

If not specified, the resource returned by the last run query is used.

Top

method get_columns()

mixed get_columns ( [ resource $resource = ''] )

Returns an array of associative arrays with information about the columns in the MySQL result associated with the specified result identifier.

Each entry will have the column's name as index and, associated, an array with the following keys:

  • name
  • table
  • def
  • max_length
  • not_null
  • primary_key
  • multiple_key
  • unique_key
  • numeric
  • blob
  • type
  • unsigned
  • zerofill
  1. // run a query
  2. $db->query('SELECT * FROM table');
  3.  
  4. // print information about the columns
  5. print_r('<pre>');
Tags:
return: Returns an associative array with information about the columns in the MySQL result associated with the specified result identifier or FALSE on error.
since: 2.0
Parameters:
resource $resource

(Optional) Resource to fetch columns information from.

If not specified, the resource returned by the last run query is used.

Top

method get_link()

identifier get_link ( )

Returns the MySQL link identifier associated with the current connection to the MySQL server.

Why a separate method? Because the library uses "lazy connection" (it is not actually connecting to the database until the first query is executed) there's no link identifier available when calling the connect() method.

  1. // create the database object
  2. $db new Zebra_Database();
  3.  
  4. // nothing is returned by this method!
  5. $db->connect('host''username''password''database');
  6.  
  7. // get the link identifier
  8. $link $db->get_link();
Tags:
return: Returns the MySQL link identifier associated with the current connection to the MySQL server.
since: 2.5
Top

method get_tables()

array get_tables ( )

Returns an array with all the tables in the current database.

  1. // get all tables from database
  2. $tables get_tables();
Tags:
return: An array with all the tables in the current database.
since: 1.1.2
Top

method get_table_columns()

array get_table_columns ( string $table )

Returns information about the columns of a given table, as an associative array.

  1. // get column information for a table named "table_name"
  2. $db->get_columns('table_name');
Tags:
return: Returns information about the columns of a given table, as an associative array.
since: 2.6
Parameters:
string $table Name of table to return column information for.
Top

method get_table_status()

array get_table_status ( [ string $pattern = ''] )

Returns an associative array with a lot of useful information on all or specific tables only.

  1. // return status information on tables having their name starting with "users"
  2. $tables get_table_status('users%');
Tags:
return: Returns an associative array with a lot of useful information on all or specific tables only.
since: 1.1.2
Parameters:
string $pattern

(Optional) Instructs the method to return information only on tables whose name matches the given pattern.

Can be a table name or a pattern with "%" as wildcard.

Top

method halt()

void halt ( )

Stops the execution of the script at the line where this method is called and, if debug is set to TRUE and the viewer's IP address is in the debugger_ip array (or debugger_ip is an empty array), shows the debug console.

Tags:
since: 1.0.7
Top

method implode()

string implode ( array $pieces )

Works similarly to PHP's implode() function, with the difference that the "glue" is always the comma and that this method escape()'s arguments.

Useful for escaping an array's values used in SQL statements with the "IN" keyword.

  1. $array array(1,2,3,4);
  2.  
  3. //  INCORRECT
  4.  
  5. //  this would not work as the WHERE clause in the SQL statement would become
  6. //  WHERE column IN ('1,2,3,4')
  7. $db->query('
  8.     SELECT
  9.         column
  10.     FROM
  11.         table
  12.     WHERE
  13.         column IN (?)
  14. 'array($array));
  15.  
  16. //  CORRECT
  17.  
  18. //  this would work as the WHERE clause in the SQL statement would become
  19. //  WHERE column IN ('1','2','3','4') which is what we actually need
  20. $db->query('
  21.     SELECT
  22.         column
  23.     FROM
  24.         table
  25.     WHERE
  26.         column IN (' $db->implode($array')
  27. ');
Tags:
return: Returns the string representation of all the array elements in the same order, escaped and with commas between each element.
since: 2.0
Parameters:
array $pieces An array with items to be "glued" together
Top

method insert()

boolean insert ( string $table , array $columns , [ boolean $ignore = false] , [ boolean $highlight = false] )

Shorthand for INSERT queries.

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escaped.

  1. $db->insert(
  2.     'table',
  3.     array(
  4.         'column1'   =>  'value1',
  5.         'column2'   =>  'value2',
  6. ));
Tags:
return: Returns TRUE on success of FALSE on error.
since: 1.0.9
Parameters:
string $table Table in which to insert.
array $columns

An associative array where the array's keys represent the columns names and the array's values represent the values to be inserted in each respective column.

Column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escape()d.

boolean $ignore

(Optional) By default, trying to insert a record that would cause a duplicate entry for a primary key would result in an error. If you want these errors to be skipped set this argument to TRUE.

For more information see MySQL's INSERT IGNORE syntax.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method insert_bulk()

boolean insert_bulk ( string $table , array $columns , arrays $data , [ boolean $ignore = false] )

Shorthand inserting multiple rows in a single query.

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escaped.

  1.     'table',
  2.     array('column1''column2'),
  3.     array(
  4.         array('value1''value2'),
  5.         array('value3''value4'),
  6.         array('value5''value6'),
  7.         array('value7''value8'),
  8.         array('value9''value10')
  9.     )
  10. ));
Tags:
return: Returns TRUE on success of FALSE on error.
since: 2.1
Parameters:
string $table Table in which to insert.
array $columns

An array with columns to insert values into.

Column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names).

arrays $data

An array of an unlimited number of arrays containing values to be inserted.

Values will be automatically escape()d.

boolean $ignore

(Optional) By default, trying to insert a record that would cause a duplicate entry for a primary key would result in an error. If you want these errors to be skipped set this argument to TRUE.

For more information see MySQL's INSERT IGNORE syntax.

Default is FALSE.

Top

method insert_id()

mixed insert_id ( )

Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.

Tags:
return: The ID generated for an AUTO_INCREMENT column by the previous INSERT query on success, '0' if the previous query does not generate an AUTO_INCREMENT value, or FALSE if there was no MySQL connection.
since: 1.0.4
Top

method insert_update()

boolean insert_update ( string $table , array $columns , [ array $update = array()] , [ boolean $highlight = false] )

When using this method, if a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.

Read more at http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html.

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escaped.

  1. // presuming article_id is a UNIQUE index or PRIMARY KEY, the statement below will insert a new row for given
  2. // $article_id and set the "votes" to 0. But, if $article_id is already in the database, increment the votes'
  3. // numbers.
  4.     'table',
  5.     array(
  6.         'article_id'    =>  $article_id,
  7.         'votes'         =>  0,
  8.     ),
  9.     array(
  10.         'votes'         =>  'INC(1)',
  11.     )
  12. );
Tags:
return: Returns TRUE on success of FALSE on error.
since: 2.1
Parameters:
string $table Table in which to insert/update.
array $columns

An associative array where the array's keys represent the columns names and the array's values represent the values to be inserted in each respective column.

Column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escape()d.

array $update

(Optional) An associative array where the array's keys represent the columns names and the array's values represent the values to be inserted in each respective column.

This array represents the columns/values to be updated if the inserted row would cause a duplicate value in a UNIQUE index or PRIMARY KEY.

If an empty array is given, the values in $columns will be used.

Column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escape()d.

A special value may also be used for when a column's value needs to be incremented or decremented. In this case, use INC(value) where value is the value to increase the column's value with. Use INC(-value) to decrease the column's value. See update() for an example.

Default is an empty array.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method language()

void language ( string $language )

Sets the language to be used for messages in the debug console.

  1. // show messages in the debug console in German
  2. $db->language('german');
Tags:
since: 1.0.6
Parameters:
string $language

The name of the PHP language file from the "languages" subdirectory.

Must be specified without the extension! (i.e. "german" for the german language not "german.php")

Default is "english".

Top

method optimize()

void optimize ( )

Optimizes all tables that have overhead (unused, lost space)

  1. // optimize all tables in the database
  2. $db->optimize();
Tags:
since: 1.1.2
Top

method parse_file()

boolean parse_file ( string $path )

Parses a MySQL dump file (like an export from phpMyAdmin).

If you must parse a very large file and your script crashed due to timeout or because of memory limitations, try the following:

  1. // prevent script timeout
  2.  
  3. // allow for more memory to be used by the script
  4. ini_set('memory_limit','128M');
Tags:
return: Returns TRUE on success or FALSE on failure.
Parameters:
string $path Path to the file to be parsed.
Top

method query()

mixed query ( string $sql , [ array $replacements = ''] , [ mixed $cache = false] , [ boolean $calc_rows = false] , [ boolean $highlight = false] )

Runs a MySQL query.

After a SELECT query you can get the number of returned rows by reading the returned_rows property.

After an UPDATE, INSERT or DELETE query you can get the number of affected rows by reading the affected_rows property.

Note that you don't need to return the result of this method in a variable for using it later with a fetch method, like fetch_assoc() or fetch_obj() as all these methods, if called without the resource arguments, work on the LAST returned result resource!

  1. // run a query
  2. $db->query('
  3.     SELECT
  4.         *
  5.     FROM
  6.         users
  7.     WHERE
  8.         gender = ?
  9. 'array($gender));
Tags:
return:

On success, returns a resource or an array (if results are taken from the cache) or FALSE on error.

If query results are taken from cache, the returned result will be a pointer to the actual results of the query!

Parameters:
string $sql MySQL statement to execute.
array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $sql. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $calc_rows

(Optional) If query is a SELECT query, this argument is set to TRUE, and there is a LIMIT applied to the query, the value of the found_rows property (after the query was run) will represent the number of records that would have been returned if there was no LIMIT applied to the query.

This is very useful for creating pagination or computing averages. Also, note that this information will be available without running an extra query. Here's how http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method seek()

boolean seek ( integer $row , [ resource $resource = ''] )

Moves the internal row pointer of the MySQL result associated with the specified result identifier to the specified row number.

The next call to a fetch method, like fetch_assoc() or fetch_obj(), would return that row.

Tags:
return: Returns TRUE on success or FALSE on failure.
since: 1.1.0
Parameters:
integer $row

The row you want to move the pointer to.

$row starts at 0.

$row should be a value in the range from 0 to returned_rows

resource $resource

(Optional) Resource to fetch.

If not specified, the resource returned by the last run query is used.

Top

method select()

mixed select ( string $columns , string $table , [ string $where = ''] , [ array $replacements = ''] , [ string $order = ''] , [ mixed $limit = ''] , [ mixed $cache = false] , [ boolean $highlight = false] , [ boolean $calc_rows = false] )

Shorthand for simple SELECT queries.

For complex queries (using UNION, JOIN, etc) use the query() method.

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escaped.

  1. $db->select(
  2.     'column1, column2',
  3.     'table',
  4.     'criteria = ?',
  5.     array($criteria)
  6. );
Tags:
return:

On success, returns a resource or an array (if results are taken from the cache) or FALSE on error.

If query results are taken from cache, the returned result will be a pointer to the actual results of the query!

since: 2.0
Parameters:
string $columns Any string representing valid column names as used in a SELECT statement.
string $table Table in which to search.
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

string $order

(Optional) A MySQL ORDER BY clause (without the ORDER BY keyword).

Default is "" (an empty string).

mixed $limit

(Optional) A MySQL LIMIT clause (without the LIMIT keyword).

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the script on whether it should cache the query's results or not. Can be either FALSE - meaning no caching - or an integer representing the number of seconds after which the cached results are considered to be expired and the query will be executed again.

The caching method is specified by the value of the caching_method property.

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

boolean $calc_rows

(Optional) If query is a SELECT query, this argument is set to TRUE, and there is a LIMIT applied to the query, the value of the found_rows property (after the query was run) will represent the number of records that would have been returned if there was no LIMIT applied to the query.

This is very useful for creating pagination or computing averages. Also, note that this information will be available without running an extra query. Here's how http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

Default is FALSE.

Top

method set_charset()

void set_charset ( [ string $charset = 'utf8'] , [ string $collation = 'utf8_general_ci'] )

Sets MySQL character set and collation.

The ensure that data is both properly saved and retrieved from the database you should call this method, first thing after connecting to the database.

If this method is not called, a warning message will be displayed in the debug console.

Warnings can be disabled by setting the disable_warnings property.

Tags:
since: 2.0
Parameters:
string $charset

(Optional) The character set to be used by the database.

Default is 'utf8'.

For a list of possible values see: http://dev.mysql.com/doc/refman/5.1/en/charset-charsets.html

string $collation

(Optional) The collation to be used by the database.

Default is 'utf8_general_ci'.

For a list of possible values see: http://dev.mysql.com/doc/refman/5.1/en/charset-charsets.html

Top

method show_debug_console()

void show_debug_console ( [ boolean $return = false] )

Shows the debug console, if debug is TRUE and the viewer's IP address is in the debugger_ip array (or $debugger_ip is an empty array).

This method must be called after all the queries in a script, preferably before </body>!

You should ALWAYS have this method called at the end of your scripts and control whether the debug console will show or not with the debug property.

Parameters:
boolean $return

(Optional) If set to TRUE, the output will be returned instead of being printed to the screen.

Default is FALSE.

Top

method table_exists()

boolean table_exists ( string $table )

Checks whether a table exists in the current database.

  1. // checks whether table "users" exists
  2. table_exists('users');
Tags:
return: Returns TRUE if table given as argument exists in the database or FALSE if not.
since: 2.3
Parameters:
string $table The name of the table to check if it exists in the database.
Top

method transaction_complete()

boolean transaction_complete ( )

Ends a transaction which means that if all the queries since transaction_start() are valid, it writes the data to the database, but if any of the queries had an error, ignore all queries and treat them as if they never happened.

  1. // start transactions
  2.  
  3. // run queries
  4.  
  5. // if all the queries since "transaction_start" are valid, write data to the database;
  6. // if any of the queries had an error, ignore all queries and treat them as if they never happened
Tags:
return: Returns TRUE on success or FALSE on error.
since: 2.1
Top

method transaction_start()

boolean transaction_start ( [ boolean $test_only = false] )

Starts the transaction system.

Transactions work only with databases that support transaction-safe table types. In MySQL, these are InnoDB or BDB table types. Working with MyISAM tables will not raise any errors but statements will be executed automatically as soon as they are called (just like if there was no transaction).

If you are not familiar with transactions, have a look at http://dev.mysql.com/doc/refman/5.0/en/commit.html and try to find a good online resource for more specific information.

  1. // start transactions
  2.  
  3. // run queries
  4.  
  5. // if all the queries since "transaction_start" are valid, write data to database;
  6. // if any of the queries had an error, ignore all queries and treat them as if they never happened
Tags:
return: Returns TRUE on success or FALSE on error.
since: 2.1
Parameters:
boolean $test_only

(Optional) Starts the transaction system in "test mode", causing the queries to be rolled back (when transaction_complete() is called ) - even if all queries are valid.

Default is FALSE.

Top

method truncate()

boolean truncate ( string $table , [ boolean $highlight = false] )

Shorthand for truncating tables.

Truncating a table is quicker then deleting all rows, as stated in the MySQL documentation at http://dev.mysql.com/doc/refman/4.1/en/truncate-table.html. Truncating a table also resets the value of the AUTO INCREMENT column.

  1. $db->truncate('table');
Tags:
return: Returns TRUE on success of FALSE on error.
since: 1.0.9
Parameters:
string $table Table to truncate.
boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method update()

boolean update ( string $table , array $columns , [ string $where = ''] , [ array $replacements = ''] , [ boolean $highlight = false] )

Shorthand for UPDATE queries.

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escaped.

After an update, see affected_rows to find out how many rows were affected.

  1. $db->update(
  2.     'table',
  3.     array(
  4.         'column1'   =>  'value1',
  5.         'column2'   =>  'value2',
  6.     ),
  7.     'criteria = ?',
  8.     array($criteria)
  9. );
Tags:
return: Returns TRUE on success of FALSE on error
since: 1.0.9
Parameters:
string $table Table in which to update.
array $columns

An associative array where the array's keys represent the columns names and the array's values represent the values to be inserted in each respective column.

Column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically escape()d.

A special value may also be used for when a column's value needs to be incremented or decremented. In this case, use INC(value) where value is the value to increase the column's value with. Use INC(-value) to decrease the column's value:

  1. $db->update(
  2.     'table',
  3.     array(
  4.         'column'    =>  'INC(?)',
  5.     ),
  6.     'criteria = ?',
  7.     array(
  8.         $value,
  9.         $criteria
  10.     )
  11. );

...is equivalent to

  1. $db->query('UPDATE table SET column = colum + ? WHERE criteria = ?'array($value$criteria));
string $where

(Optional) A MySQL WHERE clause (without the WHERE keyword).

Default is "" (an empty string).

array $replacements

(Optional) An array with as many items as the total parameter markers ("?", question marks) in $column, $table and $where. Each item will be automatically escape()-ed and will replace the corresponding "?".

Default is "" (an empty string).

boolean $highlight

(Optional) If set to TRUE, the debug console will open automatically and will show the query.

Default is FALSE.

Top

method write_log()

void write_log ( )

Writes debug information to a log.txt log file at log_path if debug is TRUE and the viewer's IP address is in the debugger_ip array (or $debugger_ip is an empty array).

This method must be called after all the queries in a script!

Make sure you're calling it BEFORE show_debug_console() so that you can see in the debug console if writing to the log file was successful or not.

Tags:
since: 1.1.0
Top