Package: Zebra_Database

Class: Zebra_Database

source file: /Zebra_Database.php

Class Overview


An advanced, compact and lightweight MySQL database wrapper library, built around PHP's MySQLi extension. It provides methods for interacting with MySQL databases that are more secure, 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.9.3 (last revision: February 19, 2016)

Copyright:

  • (c) 2006 - 2016 Stefan Gabos

Class properties

integer $affected_rows

After an INSERT, UPDATE, REPLACE or DELETE query this property will hold the number of rows that were affected by its execution. .

For the number of rows returned by SELECT queries see the $returned_rows property.

  1. // update some columns in a table
  2. $db->update('table'array(
  3.     'column_1'  =>  'value 1',
  4.     'column_2'  =>  'value 2',
  5. )'id = ?'array($id));
  6.  
  7. // print the number of affected rows
  8. echo $db->affected_rows;
Tags:
access: public
Top

string $cache_path

Path (with trailing slash) where to cache queries results.

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

Tags:
access: public
Top

string $caching_method

The method to be used for caching query results.

Can be either:

  • disk - query results are cached as files on the disk at the path specified by cache_path.
  • session - query results are cached in the session (use this only for small data sets). Note that when using this method for caching results, the library expects an active session, or will trigger a fatal error otherwise!
  • 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 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 now it is the 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
access: public
Top

integer $console_show_records

Sets the number records returned by SELECT queries to be shown in the debugging console.

  1. // show 50 records

Be aware that having this property set to a high number (hundreds), and having queries that returnthat 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
access: public
Top

boolean $debug

Setting this property to TRUE will instruct the library to generate debugging information for each query it executes.

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

Don't forget to set this to FALSE on the production environment. Generating the debugging information consumes a lot of resources and is meant to be used *only* in the development process!.

I recommend always calling the show_debug_console() method at the end of your scripts, and simply changing the value of the debug property to suit your needs, as show_debug_console() will not display anything if debug is FALSE.

Remember that on a production server you will not be left in the dark by setting this property to FALSE, as the library will try to write any errors to PHP's error log file, if your environment is configured to do so!

  1. // disable the generation of debugging information
  2. $db->debug false;

Default is TRUE.

Tags:
access: public
Top

array $debugger_ip

An array of IP addresses for which, if the debug property is set to TRUE, the show_debug_console() method should produce output.

An empty array would display the debugging console for everybody.

  1. // show the debugging console only to specific IPs
  2. $db->debugger_ip array('xxx.xxx.xxx.xxx''yyy.yyy.yyy.yyy');

Default is an empty array.

Tags:
since: 1.0.6
access: public
Top

boolean $disable_warnings

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

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

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

Default is TRUE.

Tags:
access: public
Top

integer $found_rows

After running a SELECT query 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 the same as the value of the returned_rows property.

  1. // let's assume that "table" has 100 rows
  2. // but we're only selecting the first 10 of those
  3. // the last argument of the method tells the library
  4. // to get the total number of records in the table
  5. $db->query('
  6.     SELECT
  7.         *
  8.     FROM
  9.         table
  10.     WHERE
  11.         something = ?
  12.     LIMIT
  13.         10
  14. 'array($somevalue)falsetrue);
  15.  
  16. // prints "10"
  17. // as this is the number of records
  18. // returned by the query
  19. echo $db->returned_rows;
  20.  
  21. // prints "100"
  22. // because we set the "calc_rows" argument of the
  23. // "query" method to TRUE
  24. echo $db->found_rows;
Tags:
access: public
Top

boolean $halt_on_errors

When the value of this property is set to TRUE, the execution of the script will be halted for any unsuccessful query and the debugging console will be shown, if the value of the debug property 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 for unsuccessful queries (if possible)
  2. $db->halt_on_errors false;

Default is TRUE.

Tags:
since: 1.0.5
access: public
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 library 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 SOMETHING 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 debugging console);

Tags:
access: public
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.

Tags:
access: public
Top

boolean $memcache_compressed

Setting this property to TRUE will instruct to library to compress (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
access: public
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
access: public
Top

string $memcache_key_prefix

The prefix for the keys used to identify cached queries in memcache. This allows sepparate caching of the same queries by multiple instances of the libraries, or the same instance handling multiple domains on the same memcache server.

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

Default is "" (an empty string).

Tags:
since: 2.8.4
access: public
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
access: public
Top

boolean $minimize_console

By setting this property to TRUE a minimized version of the debugging console will be shown by default, instead of the full-sized one.

Clicking on it will show the full debugging console.

For quick and easy debugging, setting the highlight argument of a method that has it will result in the debugging console being shown at full size and with the respective query visible for inspecting.

Default is TRUE

Tags:
since: 1.0.4
access: public
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. The notification email will be automatically sent to the address defined by notification_address and having notifier_domain in subject.

  1. // the email address where to send an email when there are slow queries
  2. $db->notification_address 'youremail@yourdomain.com';
Tags:
access: public
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 and 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';
Tags:
access: public
Top

string $resource_path

Path (without leading slash) to parent of public folder containing the css and javascript folders.

The path must be relative to your $_SERVER['DOCUMENT_ROOT'] and not the class' path!

Tags:
access: public
Top

integer $returned_rows

After running a SELECT query through either select() or query() methods this property would contain the number of returned rows.

See found_rows also.

  1. $db->query('
  2.     SELECT
  3.         *
  4.     FROM
  5.         table
  6.     WHERE
  7.         something = ?
  8.     LIMIT
  9.         10
  10. 'array($somevalue));
  11.  
  12. // prints "10"
  13. // as this is the number of records
  14. // returned by the query
  15. echo $db->returned_rows;
Tags:
since: 1.0.4
access: public
Top

Class methods

constructor __construct()

void __construct ( )

Constructor of the class

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 , [ string $port = ''] , [ string $socket = ''] , [ 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), the object representing the connection to the MySQL server is not available at this time. If you need it, 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 debugging console
  5. $db->connect('host''username''password''database');
  6.  
  7. //  code goes here
  8.  
  9. // show the debugging console (if enabled)
Parameters:
string $host

The address of the MySQL server to connect to (i.e. localhost).

Prepending host by p: opens a persistent connection.

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.
string $port

(Optional) The port number to attempt to connect to the MySQL server.

Leave as empty string to use the default as returned by ini_get("mysqli.default_port").

string $socket

(Optional) The socket or named pipe that should be used.

Leave as empty string to use the default as returned by ini_get("mysqli.default_socket").

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host argument.

boolean $connect

(Optional) Setting this argument to TRUE will force the library to connect to the database right away instead of using a "lazy connection" where the actual connection to the database will be made when the first query is run.

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 you will stay clear of SQL injections
  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 if there was an 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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the library 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 cache will be considered expired and the query 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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 you will stay clear of SQL injections
  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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

boolean $highlight

(Optional) If set to TRUE the debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 you will stay clear of SQL injections
  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 if there was an 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. 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 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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the library 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 cache will be considered expired and the query 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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 you will stay clear of SQL injections
  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 if there was an 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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the library 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 cache will be considered expired and the query 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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 you will stay clear of SQL injections
  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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the library 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 cache will be considered expired and the query 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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

Default is FALSE.

Top

method error()

void error ( )

Returns a string description of the last error, or an empty string if no error occurred.

In most cases you should not need this method as any errors are reported to the console when the debug property is set to TRUE, or to PHP's error log file (if your environment is configured to do so) when set to FALSE.

If, for some reasons, none of the above is available, you can use this method to catch errors.

  1. $db->query('
  2.     SELECT
  3.         *
  4.     FROM
  5.         users
  6.     WHERE
  7.         invalid_column = ?
  8. 'array($value)) or die($db->error());
Tags:
since: 2.9.1
Top

method escape()

string escape ( string $string )

Escapes special characters in a string that's to be used in an SQL statement in order to prevent SQL injections.

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 quoted string with special characters escaped in order to prevent SQL injections. .
Parameters:
string $string String to be quoted and 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. // 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_assoc()) {
  6.  
  7.     // code goes here
  8.  
  9. }
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) Name of a column containing unique values.

If specified, the returned associative array's keys will be the values from this column.

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, the returned associative array's keys will be the values from this column.

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 free_result()

void free_result ( resource $resource )

Frees the memory associated with a result

You should always free your result with free_result(), when your result object is not needed anymore.

Tags:
since: 2.9.1
Parameters:
resource $resource

A resource returned by query or select methods.

The method will do nothing if the argument is not a valid resource.

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 key 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_selected_database()

mixed get_selected_database ( )

Returns the name of the currently selected database.

Tags:
return: Returns the name of the currently selected database, or FALSE if there's no active connection.
since: 2.8.7
access: public
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_table_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 debugging 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.

This was useful for escaping an array's values used in SQL statements with the "IN" keyword, before adding arrays directly in the replacement array became possible in version 2.8.6

  1. $array array(1,2,3,4);
  2.  
  3. //  this would work as the WHERE clause in the SQL statement would become
  4. //  WHERE column IN ('1','2','3','4')
  5. $db->query('
  6.     SELECT
  7.         column
  8.     FROM
  9.         table
  10.     WHERE
  11.         column IN (' $db->implode($array')
  12. ');
  13.  
  14. //  THE RECOMMENDED WAY OF DOING WHERE-IN CONDITIONS SINCE VERSION 2.8.6
  15.  
  16. $db->query('
  17.     SELECT
  18.         column
  19.     FROM
  20.         table
  21.     WHERE
  22.         column IN (?)
  23. 'array($array));
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 escape()d in order to prevent SQL injections.

  1. // notice that we're also using MySQL functions within values
  2. $db->insert(
  3.     'table',
  4.     array(
  5.         'column1'       =>  'value1',
  6.         'column2'       =>  'TRIM(UCASE("value2"))',
  7.         'date_updated'  =>  'NOW()',
  8. ));
  9.  
  10. // when using MySQL functions, the value will be used as it is without being escaped!
  11. // while this is ok when using a function without any arguments like NOW(), this may
  12. // pose a security concern if the argument(s) come from user input.
  13. // in this case we have to escape the value ourselves
  14. $db->insert(
  15.     'table',
  16.     array(
  17.         'column1'       =>  'value1',
  18.         'column2'       =>  'TRIM(UCASE("' $db->escape($value'"))',
  19.         'date_updated'  =>  'NOW()',
  20. ));
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 in order to prevent SQL injections.

You may also use any of MySQL's functions as values.

Be aware that when using MySQL functions, the value will be used as it is without being escaped! While this is ok when using a function without any arguments like NOW(), this may pose a security concern if the argument(s) come from user input. In this case make sure you escape the values yourself!

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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

Default is FALSE.

Top

method insert_bulk()

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

Shorthand for 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 escape()d in order to prevent SQL injections.

  1. // notice that we're also using MySQL functions within values
  2.     'table',
  3.     array('column1''column2''date_updated'),
  4.     array(
  5.         array('value1''TRIM(UCASE("value2"))''NOW()'),
  6.         array('value3''TRIM(UCASE("value4"))''NOW()'),
  7.     )
  8. );
  9.  
  10. // when using MySQL functions, the value will be used as it is without being escaped!
  11. // while this is ok when using a function without any arguments like NOW(), this may
  12. // pose a security concern if the argument(s) come from user input.
  13. // in this case we have to escape the value ourselves
  14.     'table',
  15.     array('column1''column2''date_updated'),
  16.     array(
  17.         array('value1''TRIM(UCASE("' $db->escape($value2'"))''NOW()'),
  18.         array('value3''TRIM(UCASE("' $db->escape($value4'"))''NOW()'),
  19.     )
  20. );
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).

array $data

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

Values will be automatically escape()d in order to prevent SQL injections.

You may also use any of MySQL's functions as values.

Be aware that when using MySQL functions, the value will be used as it is without being escaped! While this is ok when using a function without any arguments like NOW(), this may pose a security concern if the argument(s) come from user input. In this case make sure you escape the values yourself!

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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 here.

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 escape()d in order to prevent SQL injections.

  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. // also notice that we're using a MySQL function as a value
  5.     'table',
  6.     array(
  7.         'article_id'    =>  $article_id,
  8.         'votes'         =>  0,
  9.         'date_updated'  =>  'NOW()',
  10.     ),
  11.     array(
  12.         'votes'         =>  'INC(1)',
  13.     )
  14. );
  15.  
  16. // when using MySQL functions, the value will be used as it is without being escaped!
  17. // while this is ok when using a function without any arguments like NOW(), this may
  18. // pose a security concern if the argument(s) come from user input.
  19. // in this case we have to escape the value ourselves
  20.     'table',
  21.     array(
  22.         'article_id'    =>  'CEIL("' $db->escape($article_id'")',
  23.         'votes'         =>  0,
  24.         'date_updated'  =>  'NOW()',
  25.     ),
  26.     array(
  27.         'votes'         =>  'INC(1)',
  28.     )
  29. );
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.

You may also use any of MySQL's functions as values.

Be aware that when using MySQL functions, the value will be used as it is without being escaped! While this is ok when using a function without any arguments like NOW(), this may pose a security concern if the argument(s) come from user input. In this case make sure you escape the values yourself!

array $update

(Optional) An associative array where the array's keys represent the columns names and the array's values represent the values to update the columns' values to.

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.

You may also use any of MySQL's functions as values.

Be aware that when using MySQL functions, the value will be used as it is without being escaped! While this is ok when using a function without any arguments like NOW(), this may pose a security concern if the argument(s) come from user input. In this case make sure you escape the values yourself!

Default is an empty array.

boolean $highlight

(Optional) If set to TRUE the debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

Default is FALSE.

Top

method language()

void language ( string $language )

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

  1. // show messages in the debugging 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));
  10.  
  11. // array as replacement, for use with WHERE-IN conditions
  12. $db->query('
  13.     SELECT
  14.         *
  15.     FROM
  16.         users
  17.     WHERE
  18.         gender = ? AND
  19.         id IN (?)
  20. 'array('f'array(123)));
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 "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions.

Default is "" (an empty string).

mixed $cache

(Optional) Instructs the library 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 cache will be considered expired and the query 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

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE the debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 ( mixed $columns , string $table , [ string $where = ''] , [ array $replacements = ''] , [ string $order = ''] , [ mixed $limit = ''] , [ mixed $cache = false] , [ boolean $calc_rows = false] , [ boolean $highlight = 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 escape()d in order to prevent SQL injections.

  1. $db->select(
  2.     'column1, column2',
  3.     'table',
  4.     'criteria = ?',
  5.     array($criteria)
  6. );
  7.  
  8. // or
  9.  
  10. $db->select(
  11.     array('column1''column2'),
  12.     'table',
  13.     'criteria = ?',
  14.     array($criteria)
  15. );
  16.  
  17. // or
  18.  
  19. $db->select(
  20.     '*',
  21.     'table',
  22.     'criteria = ?',
  23.     array($criteria)
  24. );
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:
mixed $columns

A string with comma separated values or an array representing valid column names as used in a SELECT statement.

These will be enclosed in grave accents, so make sure you are only using column names and not things like "tablename.*"! You may also use "*" instead of column names to select all columns from a table.

string $table

Table in which to search.

Note that table name will be enclosed in grave accents " ` " and thus only one table name should be used! For anything but a simple select query use the query() method.

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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

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 library 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 cache will be considered expired and the query 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

Default is FALSE.

boolean $highlight

(Optional) If set to TRUE the debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 debugging 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'.

See the list of possible values

string $collation

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

Default is 'utf8_general_ci'.

See the list of possible values

Top

method show_debug_console()

void show_debug_console ( [ boolean $return = false] )

Shows the debugging 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 debugging 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 here 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. 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 debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

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 escape()d in order to prevent SQL injections.

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

  1. // notice that we're using a MySQL function as a value
  2. $db->update(
  3.     'table',
  4.     array(
  5.         'column1'       =>  'value1',
  6.         'column2'       =>  'value2',
  7.         'date_updated'  =>  'NOW()',
  8.     ),
  9.     'criteria = ?',
  10.     array($criteria)
  11. );
  12.  
  13. // when using MySQL functions, the value will be used as it is without being escaped!
  14. // while this is ok when using a function without any arguments like NOW(), this may
  15. // pose a security concern if the argument(s) come from user input.
  16. // in this case we have to escape the value ourselves
  17. $db->update(
  18.     'table',
  19.     array(
  20.         'column1'       =>  'TRIM(UCASE("' $db->escape($value1'"))',
  21.         'column2'       =>  'value2',
  22.         'date_updated'  =>  'NOW()',
  23.     ),
  24.     'criteria = ?',
  25.     array($criteria)
  26. );
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));

You may also use any of MySQL's functions as values.

Be aware that when using MySQL functions, the value will be used as it is without being escaped! While this is ok when using a function without any arguments like NOW(), this may pose a security concern if the argument(s) come from user input. In this case make sure you escape the values yourself!

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 $where. Each item will be automatically escape()-ed and will replace the corresponding "?". Can also include an array as an item, case in which each value from the array will automatically escape()-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example here.

Default is "" (an empty string).

boolean $highlight

(Optional) If set to TRUE the debugging console will be opened automatically and the query will be shown - really useful for quick and easy debugging.

Default is FALSE.

Top

method write_log()

void write_log ( [ boolean $daily = false] , [ boolean $hourly = false] )

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 debugging console if writing to the log file was successful or not.

Note that by default all logs are written to a single file. Refer to the method's arguments for grouping logs by days and/or hours.

Tags:
since: 1.1.0
Parameters:
boolean $daily

Should logs be grouped by days?

Log files will have their name in the form of "log_ymd.txt", where "y", "m" and "d" represent two digit values for year, month and day, respectively.

Default is FALSE.

boolean $hourly

Should logs be also groupped by hours?

Log files will have their name in the form of "log_ymd_h.txt", where "y", "m" and "d" represent two digit values for year, month and day, respectively, while "h" represents the two digit value for hour.

Note that if this argument is set to TRUE, the $daily argument will be automatically set to TRUE.

Default is FALSE.

Top