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!
// after an "action" query...
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.// the host where memcache is listening for connections
// the port where memcache is listening for connections
// for this to work, php needs to be configured with --with-zlib[=dir] !
// set it to FALSE otherwise
// cache queries using the memcache server
// only after we've set up everything it is time to 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:
Top
integer $console_show_records
Sets how many of the records returned by a SELECT query should be shown in the debug console.
// 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:
// set PHP's memory limit to 20 MB
Default is 20.
Tags:
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.
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.
// show the debug console only to specific IPs
$db->debugger_ip =
array('192.168.0.12', '192.168.0.13');
Default is an empty array.
Tags:
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).
// don't stop execution on critical errors (if possible)
Default is TRUE.
Tags:
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.
// consider queries running for more than 5 seconds as slow and send email
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:
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:
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:
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:
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.
// the email address where to send an email when there are slow queries
$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.
// set a domain name so that you'll know where the email comes from
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.
// after a select query...
Tags:
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.
// create the database object
// notice that we're not doing any error checking. errors will be shown in the debug console
$db->connect('host', 'username', 'password', 'database');
// code goes here
// 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.
// count male users
$male =
$db->dcount('id', 'users', 'gender = "M"');
// when working with variables you should use the following syntax
// this way variables will be mysqli_real_escape_string-ed first
$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.
// delete male users
$db->delete('users', 'gender = "M"');
// when working with variables you should use the following syntax
// this way variables will be mysqli_real_escape_string-ed first
$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.
// get name, surname and age of all male users
$result =
$db->dlookup('name, surname, age', 'users', 'gender = "M"');
// when working with variables you should use the following syntax
// this way variables will be mysqli_real_escape_string-ed first
$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.
// get the maximum age of male users
$result =
$db->dmax('age', 'users', 'gender = "M"');
// when working with variables you should use the following syntax
// this way variables will be mysqli_real_escape_string-ed first
$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:
// get the total logins of all male users
$result =
$db->dsum('login_count', 'users', 'gender = "M"');
// when working with variables you should use the following syntax
// this way variables will be mysqli_real_escape_string-ed first
$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.
// use the method in a query
// THIS IS NOT THE RECOMMENDED METHOD!
SELECT
*
FROM
users
WHERE
gender = "' .
$db->escape($gender) .
'"
');
// the recommended method
// (variable are automatically escaped this way)
SELECT
*
FROM
users
WHERE
gender = ?
', 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.
// create the database object
// run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
// iterate through the found records
// code goes here
}
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.
// run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
// fetch all the rows as an associative array
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.
// run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
// iterate through the found records
// code goes here
}
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.
// run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
// fetch all the rows as an associative array
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
// run a query
$db->query('SELECT * FROM table');
// print information about the columns
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.
// create the database object
// nothing is returned by this method!
$db->connect('host', 'username', 'password', 'database');
// get the link identifier
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.
// get all tables from database
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.
// get column information for a table named "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.
// return status information on tables having their name starting with "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:
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.
$array = array(1,2,3,4);
// INCORRECT
// this would not work as the WHERE clause in the SQL statement would become
// WHERE column IN ('1,2,3,4')
SELECT
column
FROM
table
WHERE
column IN (?)
', array($array));
// CORRECT
// this would work as the WHERE clause in the SQL statement would become
// WHERE column IN ('1','2','3','4') which is what we actually need
SELECT
column
FROM
table
WHERE
column IN (' .
$db->implode($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 escaped.
'table',
array(
'column1' => 'value1',
'column2' => 'value2',
));
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.
'table',
array('column1', 'column2'),
array(
array('value1', 'value2'),
array('value3', 'value4'),
array('value5', 'value6'),
array('value7', 'value8'),
array('value9', 'value10')
)
));
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.
// presuming article_id is a UNIQUE index or PRIMARY KEY, the statement below will insert a new row for given
// $article_id and set the "votes" to 0. But, if $article_id is already in the database, increment the votes'
// numbers.
'table',
array(
'article_id' => $article_id,
'votes' => 0,
),
array(
'votes' => 'INC(1)',
)
);
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.
// show messages in the debug console in German
Tags:
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)
// optimize all tables in the database
Tags:
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:
// prevent script timeout
// allow for more memory to be used by the script
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!
// run a query
SELECT
*
FROM
users
WHERE
gender = ?
', 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.
'column1, column2',
'table',
'criteria = ?',
array($criteria)
);
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:
Parameters:
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.
// checks whether table "users" exists
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.
// start transactions
// run queries
// if all the queries since "transaction_start" are valid, write data to the database;
// 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.
// start transactions
// run queries
// if all the queries since "transaction_start" are valid, write data to database;
// 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.
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.
'table',
array(
'column1' => 'value1',
'column2' => 'value2',
),
'criteria = ?',
array($criteria)
);
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:
'table',
array(
'column' => 'INC(?)',
),
'criteria = ?',
array(
$value,
$criteria
)
);
...is equivalent to $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:
Top