Property | Type | Description | |
---|---|---|---|
$affected_rows | integer | For the number of rows returned by SELECT queries see the {@link $returned_rows} property.
update some columns in a table
$db->update('table', array(
'column_1' => 'value 1',
'column_2' => 'value 2',
), 'id = ?', array($id));
print the number of affected rows
echo $db->affected_rows;
|
|
$cache_path | string | The path must be relative to your working path and not the class' path! | |
$caching_method | string | Can be either:
- disk - query results are cached as files on the disk at the path specified by {@link 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 {@link http://memcached.org/about memcache} server; when
using this method make sure to also set the appropriate values for {@link memcache_host},
{@link memcache_port} and optionally {@link memcache_compressed}.
For using memcache as caching method, PHP must be compiled with the {@link http://pecl.php.net/package/memcache memcache} extension and, if {@link memcache_compressed} property is set to TRUE, needs to be configured with --with-zlib[=DIR]. If caching method is set to "memcache", {@link memcache_host}, {@link memcache_port} and optionally {@link memcache_compressed} must be set prior to calling the {@link connect()} method! Failing to do so will disable caching.
the host where memcache is listening for connections
$db->memcache_host = 'localhost';
the port where memcache is listening for connections
$db->memcache_port = 11211;
for this to work, PHP needs to be configured with --with-zlib[=dir] !
set it to FALSE otherwise
$db->memcache_compressed = true;
cache queries using the memcache server
$db->caching_method = 'memcache';
only now it is the time to connect
$db->connect(...)
Caching is done on a per-query basis by setting the "cache" argument when calling some of the library's
methods like {@link query()}, {@link select()}, {@link dcount()}, {@link dlookup()}, {@link dmax()} and {@link dsum()}!
Default is "disk". |
|
$console_show_records | integer |
show 50 records
$db->console_show_records(50);
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:
set PHP's memory limit to 20 MB
ini_set('memory_limit','20M');
Default is 20. |
|
$debug | boolean | Debugging information can later be reviewed by calling the {@link 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 {@link show_debug_console()} method at the end of your scripts, and simply changing
the value of the debug property to suit your needs, as {@link 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
{@link http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors configured to do so}!
disable the generation of debugging information
$db->debug = false;
Default is TRUE. |
|
$debugger_ip | array | An empty array would display the debugging console for everybody.
show the debugging console only to specific IPs
$db->debugger_ip = array('xxx.xxx.xxx.xxx', 'yyy.yyy.yyy.yyy');
Default is an empty array. |
|
$disable_warnings | boolean | 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. | |
$found_rows | integer | 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 {@link returned_rows} property.
let's assume that "table" has 100 rows
but we're only selecting the first 10 of those
the last argument of the method tells the library
to get the total number of records in the table
$db->query('
SELECT
*
FROM
table
WHERE
something = ?
LIMIT
10
', array($somevalue), false, true);
prints "10"
as this is the number of records
returned by the query
echo $db->returned_rows;
prints "100"
because we set the "calc_rows" argument of the
"query" method to TRUE
echo $db->found_rows;
|
|
$halt_on_errors | boolean |
don't stop execution for unsuccessful queries (if possible)
$db->halt_on_errors = false;
Default is TRUE. |
|
$log_path | string | The path is relative to your working directory. Data is written to the log file when calling the {@link 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 {@link http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors configured so}) only when the {@link $debug debug} property is set to FALSE (as when the debug property is set to TRUE the error messages are reported in the debugging console); | |
$max_query_time | integer | If a query's execution time exceeds this number, a notification email will be automatically sent to the address
defined by {@link notification_address}, having {@link notifier_domain} in subject.
consider queries running for more than 5 seconds as slow and send email
$db->max_query_time = 5;
Default is 10. |
|
$memcache_compressed | boolean | For this to work, PHP needs to be configured with --with-zlib[=DIR] ! Set this property only if you are using "memcache" as {@link caching_method}. Default is FALSE. | |
$memcache_host | mixed | Set this property only if you are using "memcache" as {@link caching_method}. Default is FALSE. | |
$memcache_key_prefix | string | Set this property only if you are using "memcache" as {@link caching_method}. Default is "" (an empty string). | |
$memcache_port | mixed | Set this property only if you are using "memcache" as {@link caching_method}. Default is FALSE. | |
$minimize_console | boolean | 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 | |
$notification_address | string |
the email address where to send an email when there are slow queries
$db->notification_address = '[email protected]';
|
|
$notifier_domain | string | If a query's execution time exceeds the number of seconds set by {@link max_query_time}, a notification email
will be automatically sent to the address defined by {@link notification_address} and having {@link notifier_domain}
in subject.
set a domain name so that you'll know where the email comes from
$db->notifier_domain = 'yourdomain.com';
|
|
$resource_path | string | The path must be relative to your $_SERVER['DOCUMENT_ROOT'] and not the class' path! | |
$returned_rows | integer | See {@link found_rows} also.
$db->query('
SELECT
*
FROM
table
WHERE
something = ?
LIMIT
10
', array($somevalue));
prints "10"
as this is the number of records
returned by the query
echo $db->returned_rows;
|
Method | Description | |
---|---|---|
__construct ( ) : void | Constructor of the class | |
__destruct ( ) | Frees the memory associated with the last result. | |
close ( ) : boolean | Closes the MySQL connection. | |
connect ( string $host, string $user, string $password, string $database, string $port = '', string $socket = '', boolean $connect = false ) : void | Opens a connection to a MySQL Server and selects a database. | |
dcount ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | Counts the values in a column of a table. | |
delete ( string $table, string $where = '', array $replacements = '', boolean $highlight = false ) : boolean | Deletes rows from a table. | |
dlookup ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | Returns one or more columns from ONE row of a table. | |
dmax ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | Looks up the maximum value in a column of a table. | |
dsum ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | Sums the values in a column of a table. | |
error ( ) : void | Returns a string description of the last error, or an empty string if no error occurred. | |
escape ( string $string ) : string | Escapes special characters in a string that's to be used in an SQL statement in order to prevent SQL injections. | |
fetch_assoc ( resource $resource = '' ) : mixed | 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. | |
fetch_assoc_all ( string $index = '', resource $resource = '' ) : mixed | 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. | |
fetch_obj ( resource $resource = '' ) : mixed | Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. | |
fetch_obj_all ( string $index = '', resource $resource = '' ) : mixed | 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. | |
free_result ( resource $resource ) : void | Frees the memory associated with a result | |
get_columns ( resource $resource = '' ) : mixed | Returns an array of associative arrays with information about the columns in the MySQL result associated with the specified result identifier. | |
get_link ( ) : identifier | Returns the MySQL link identifier associated with the current connection to the MySQL server. | |
get_selected_database ( ) : mixed | Returns the name of the currently selected database. | |
get_table_columns ( string $table ) : array | Returns information about the columns of a given table, as an associative array. | |
get_table_status ( string $pattern = '' ) : array | Returns an associative array with a lot of useful information on all or specific tables only. | |
get_tables ( ) : array | Returns an array with all the tables in the current database. | |
halt ( ) : void | Stops the execution of the script at the line where this method is called and, if {@link debug} is set to TRUE and the viewer's IP address is in the {@link debugger_ip} array (or debugger_ip is an empty array), shows the debugging console. | |
implode ( array $pieces ) : string | Works similarly to PHP's implode() function with the difference that the "glue" is always the comma, and that this method {@link escape()}'s arguments. | |
insert ( string $table, array $columns, boolean $ignore = false, boolean $highlight = false ) : boolean | Shorthand for INSERT queries. | |
insert_bulk ( string $table, array $columns, array $data, boolean $ignore = false, boolean $highlight = false ) : boolean | Shorthand for inserting multiple rows in a single query. | |
insert_id ( ) : mixed | Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. | |
insert_update ( string $table, array $columns, array $update = [], boolean $highlight = false ) : boolean | 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. | |
language ( string $language ) : void | Sets the language to be used for the messages in the debugging console. | |
optimize ( ) : void | Optimizes all tables that have overhead (unused, lost space) | |
parse_file ( string $path ) : boolean | Parses a MySQL dump file (like an export from phpMyAdmin). | |
query ( string $sql, array $replacements = '', mixed $cache = false, boolean $calc_rows = false, boolean $highlight = false ) : mixed | Runs a MySQL query. | |
seek ( integer $row, resource $resource = '' ) : boolean | Moves the internal row pointer of the MySQL result associated with the specified result identifier to the specified row number. | |
select ( mixed $columns, string $table, string $where = '', array $replacements = '', string $order = '', mixed $limit = '', mixed $cache = false, boolean $calc_rows = false, boolean $highlight = false ) : mixed | Shorthand for simple SELECT queries. | |
set_charset ( string $charset = 'utf8', string $collation = 'utf8_general_ci' ) : void | Sets MySQL character set and collation. | |
show_debug_console ( boolean $return = false ) : void | Shows the debugging console, if {@link debug} is TRUE and the viewer's IP address is in the {@link debugger_ip} array (or $debugger_ip is an empty array). | |
table_exists ( string $table ) : boolean | Checks whether a table exists in the current database. | |
transaction_complete ( ) : boolean | Ends a transaction which means that if all the queries since {@link 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. | |
transaction_start ( boolean $test_only = false ) : boolean | Starts the transaction system. | |
truncate ( string $table, boolean $highlight = false ) : boolean | Shorthand for truncating tables. | |
update ( string $table, array $columns, string $where = '', array $replacements = '', boolean $highlight = false ) : boolean | Shorthand for UPDATE queries. | |
write_log ( boolean $daily = false, boolean $hourly = false ) : void | Writes debug information to a log.txt log file at {@link log_path} if {@link debug} is TRUE and the viewer's IP address is in the {@link debugger_ip} array (or $debugger_ip is an empty array). |
Method | Description | |
---|---|---|
_build_columns ( $columns ) | Given an associative array or a string with comma separated values where the values represent column names, this method will enclose column names in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and automatically {@link escape()} value. | |
_build_sql ( &$columns ) | Given an associative array where the array's keys represent column names and the array's values represent the values to be associated with each respective column, this method will enclose column names in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and automatically {@link escape()} value. | |
_connected ( ) | Checks if the connection to the MySQL server has been previously established by the connect() method. | |
_fix_pow ( $value ) | PHP's microtime() will return elapsed time as something like 9.79900360107E-5 when the elapsed time is too short. | |
_is_mysql_function ( $value ) | Checks if a string is in fact a MySQL function call (or a bunch of nested MySQL functions) | |
_is_result ( $value ) | Checks is a value is a valid result set obtained from a query against the database | |
_log ( $category, $data, $fatal = true ) | Handles saving of debug information and halts the execution of the script on fatal error or if the {@link halt_on_errors} property is set to TRUE |
create the database object
$db = new Zebra_Database();
notice that we're not doing any error checking. errors will be shown in the debugging console
$db->connect('host', 'username', 'password', 'database');
code goes here
show the debugging console (if enabled)
$db->show_debug_console();
public connect ( string $host, string $user, string $password, string $database, string $port = '', string $socket = '', boolean $connect = false ) : void | ||
$host | string | The address of the MySQL server to connect to (i.e. localhost). Prepending host by p: opens a persistent connection. @param string $user The user name used for authentication when connecting to the MySQL server. @param string $password The password used for authentication when connecting to the MySQL server. @param string $database The database to be selected after the connection is established. @param 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"). @param 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. @param 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. @return void |
$user | string | |
$password | string | |
$database | string | |
$port | string | |
$socket | string | |
$connect | boolean | |
return | void |
count male users
$male = $db->dcount('id', 'users', 'gender = "M"');
when working with variables you should use the following syntax
this way you will stay clear of SQL injections
$users = $db->dcount('id', 'users', 'gender = ?', array($gender));
public dcount ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | ||
$column | string | Name of the column in which to do the counting. @param string $table Name of the table containing the column. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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. @return mixed 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. |
$table | string | |
$where | string | |
$replacements | array | |
$cache | mixed | |
$highlight | boolean | |
return | mixed |
delete male users
$db->delete('users', 'gender = "M"');
when working with variables you should use the following syntax
this way you will stay clear of SQL injections
$db->delete('users', 'gender = ?', array($gender));
public delete ( string $table, string $where = '', array $replacements = '', boolean $highlight = false ) : boolean | ||
$table | string | Table from which to delete. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param 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. @since 1.0.9 @return boolean Returns TRUE on success or FALSE on error. |
$where | string | |
$replacements | array | |
$highlight | boolean | |
return | boolean |
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 you will stay clear of SQL injections
$result = $db->dlookup('name, surname, age', 'users', 'gender = ?', array($gender));
public dlookup ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | ||
$column | string | 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. @param string $table Name of the table in which to search. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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. @return mixed 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. |
$table | string | |
$where | string | |
$replacements | array | |
$cache | mixed | |
$highlight | boolean | |
return | mixed |
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 you will stay clear of SQL injections
$result = $db->dmax('age', 'users', 'gender = ?', array($gender));
public dmax ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | ||
$column | string | Name of the column in which to search. @param string $table Name of table in which to search. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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. @return mixed 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. |
$table | string | |
$where | string | |
$replacements | array | |
$cache | mixed | |
$highlight | boolean | |
return | mixed |
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 you will stay clear of SQL injections
$result = $db->dsum('login_count', 'users', 'gender = ?', array($gender));
public dsum ( string $column, string $table, string $where = '', array $replacements = '', mixed $cache = false, boolean $highlight = false ) : mixed | ||
$column | string | Name of the column in which to sum values. @param string $table Name of the table in which to search. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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. @return mixed 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. |
$table | string | |
$where | string | |
$replacements | array | |
$cache | mixed | |
$highlight | boolean | |
return | mixed |
$db->query('
SELECT
*
FROM
users
WHERE
invalid_column = ?
', array($value)) or die($db->error());
use the method in a query
THIS IS NOT THE RECOMMENDED METHOD!
$db->query('
SELECT
*
FROM
users
WHERE
gender = "' . $db->escape($gender) . '"
');
the recommended method
(variable are automatically escaped this way)
$db->query('
SELECT
*
FROM
users
WHERE
gender = ?
', array($gender));
run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
iterate through the found records
while ($row = $db->fetch_assoc()) {
code goes here
}
public fetch_assoc ( resource $resource = '' ) : mixed | ||
$resource | resource | (Optional) Resource to fetch. If not specified, the resource returned by the last run query is used. @return mixed 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. |
return | mixed |
run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
fetch all the rows as an associative array
$records = $db->fetch_assoc_all();
public fetch_assoc_all ( string $index = '', resource $resource = '' ) : mixed | ||
$index | string | (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. @param resource $resource (Optional) Resource to fetch. If not specified, the resource returned by the last run query is used. @since 1.1.2 @return mixed 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. |
$resource | resource | |
return | mixed |
run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
iterate through the found records
while ($row = $db->fetch_obj()) {
code goes here
}
public fetch_obj ( resource $resource = '' ) : mixed | ||
$resource | resource | (Optional) Resource to fetch. If not specified, the resource returned by the last run query is used. @since 1.0.8 @return mixed 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. |
return | mixed |
run a query
$db->query('SELECT * FROM table WHERE criteria = ?', array($criteria));
fetch all the rows as an associative array
$records = $db->fetch_obj_all();
public fetch_obj_all ( string $index = '', resource $resource = '' ) : mixed | ||
$index | string | (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. @param resource $resource (Optional) Resource to fetch. If not specified, the resource returned by the last run query is used. @since 1.1.2 @return mixed 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. |
$resource | resource | |
return | mixed |
public free_result ( resource $resource ) : void | ||
$resource | resource | A resource returned by {@link query} or {@link select} methods. The method will do nothing if the argument is not a valid resource. @since 2.9.1 @return void |
return | void |
run a query
$db->query('SELECT * FROM table');
print information about the columns
print_r('
');
print_r($db->get_columns());
public get_columns ( resource $resource = '' ) : mixed | ||
$resource | resource | (Optional) Resource to fetch columns information from. If not specified, the resource returned by the last run query is used. @since 2.0 @return mixed Returns an associative array with information about the columns in the MySQL result associated with the specified result identifier, or FALSE on error. |
return | mixed |
create the database object
$db = new Zebra_Database();
nothing is returned by this method!
$db->connect('host', 'username', 'password', 'database');
get the link identifier
$link = $db->get_link();
public get_link ( ) : identifier | ||
return | identifier |
public get_selected_database ( ) : mixed | ||
return | mixed | Returns the name of the currently selected database, or FALSE if there's no active connection. |
get column information for a table named "table_name"
$db->get_table_columns('table_name');
public get_table_columns ( string $table ) : array | ||
$table | string | Name of table to return column information for. @since 2.6 @return array Returns information about the columns of a given table as an associative array. |
return | array |
return status information on tables having their name starting with "users"
$tables = get_table_status('users%');
public get_table_status ( string $pattern = '' ) : array | ||
$pattern | string | (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. @since 1.1.2 @return array Returns an associative array with a lot of useful information on all or specific tables only. |
return | array |
get all tables from database
$tables = get_tables();
public get_tables ( ) : array | ||
return | array |
$array = array(1,2,3,4);
this would work as the WHERE clause in the SQL statement would become
WHERE column IN ('1','2','3','4')
$db->query('
SELECT
column
FROM
table
WHERE
column IN (' . $db->implode($array) . ')
');
THE RECOMMENDED WAY OF DOING WHERE-IN CONDITIONS SINCE VERSION 2.8.6
$db->query('
SELECT
column
FROM
table
WHERE
column IN (?)
', array($array));
notice that we're also using MySQL functions within values
$db->insert(
'table',
array(
'column1' => 'value1',
'column2' => 'TRIM(UCASE("value2"))',
'date_updated' => 'NOW()',
));
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 we have to escape the value ourselves
$db->insert(
'table',
array(
'column1' => 'value1',
'column2' => 'TRIM(UCASE("' . $db->escape($value) . '"))',
'date_updated' => 'NOW()',
));
public insert ( string $table, array $columns, boolean $ignore = false, boolean $highlight = false ) : boolean | ||
$table | string | Table in which to insert. @param 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 {@link escape()}d in order to prevent SQL injections. You may also use any of {@link http://www.techonthenet.com/mysql/functions/ 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 {@link escape} the values yourself! @param 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 {@link http://dev.mysql.com/doc/refman/5.5/en/insert.html MySQL's INSERT IGNORE syntax}. Default is FALSE. @param 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. @since 1.0.9 @return boolean Returns TRUE on success of FALSE on error. |
$columns | array | |
$ignore | boolean | |
$highlight | boolean | |
return | boolean |
notice that we're also using MySQL functions within values
$db->insert_bulk(
'table',
array('column1', 'column2', 'date_updated'),
array(
array('value1', 'TRIM(UCASE("value2"))', 'NOW()'),
array('value3', 'TRIM(UCASE("value4"))', 'NOW()'),
)
);
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 we have to escape the value ourselves
$db->insert_bulk(
'table',
array('column1', 'column2', 'date_updated'),
array(
array('value1', 'TRIM(UCASE("' . $db->escape($value2) . '"))', 'NOW()'),
array('value3', 'TRIM(UCASE("' . $db->escape($value4) . '"))', 'NOW()'),
)
);
public insert_bulk ( string $table, array $columns, array $data, boolean $ignore = false, boolean $highlight = false ) : boolean | ||
$table | string | Table in which to insert. @param 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). @param array $data An array of an unlimited number of arrays containing values to be inserted. Values will be automatically {@link escape()}d in order to prevent SQL injections. You may also use any of {@link http://www.techonthenet.com/mysql/functions/ 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 {@link escape} the values yourself! @param 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 {@link http://dev.mysql.com/doc/refman/5.5/en/insert.html MySQL's INSERT IGNORE syntax}. Default is FALSE. @param 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. @since 2.1 @return boolean Returns TRUE on success of FALSE on error. |
$columns | array | |
$data | array | |
$ignore | boolean | |
$highlight | boolean | |
return | boolean |
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.
also notice that we're using a MySQL function as a value
$db->insert_update(
'table',
array(
'article_id' => $article_id,
'votes' => 0,
'date_updated' => 'NOW()',
),
array(
'votes' => 'INC(1)',
)
);
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 we have to escape the value ourselves
$db->insert_update(
'table',
array(
'article_id' => 'CEIL("' . $db->escape($article_id) . '")',
'votes' => 0,
'date_updated' => 'NOW()',
),
array(
'votes' => 'INC(1)',
)
);
public insert_update ( string $table, array $columns, array $update = [], boolean $highlight = false ) : boolean | ||
$table | string | Table in which to insert/update. @param 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 {@link escape()}d. You may also use any of {@link http://www.techonthenet.com/mysql/functions/ 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 {@link escape} the values yourself! @param 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 {@link 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 {@link update()} for an example. You may also use any of {@link http://www.techonthenet.com/mysql/functions/ 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 {@link escape} the values yourself! Default is an empty array. @param 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. @since 2.1 @return boolean Returns TRUE on success of FALSE on error. |
$columns | array | |
$update | array | |
$highlight | boolean | |
return | boolean |
show messages in the debugging console in German
$db->language('german');
optimize all tables in the database
$db->optimize();
prevent script timeout
set_time_limit(0);
allow for more memory to be used by the script
ini_set('memory_limit','128M');
public parse_file ( string $path ) : boolean | ||
$path | string | Path to the file to be parsed. @return boolean Returns TRUE on success or FALSE on failure. |
return | boolean |
run a query
$db->query('
SELECT
*
FROM
users
WHERE
gender = ?
', array($gender));
array as replacement, for use with WHERE-IN conditions
$db->query('
SELECT
*
FROM
users
WHERE
gender = ? AND
id IN (?)
', array('f', array(1, 2, 3)));
public query ( string $sql, array $replacements = '', mixed $cache = false, boolean $calc_rows = false, boolean $highlight = false ) : mixed | ||
$sql | string | MySQL statement to execute. @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $sql. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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 {@link 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. {@link http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows Here's how} Default is FALSE. @param 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. @return mixed 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! |
$replacements | array | |
$cache | mixed | |
$calc_rows | boolean | |
$highlight | boolean | |
return | mixed |
public seek ( integer $row, resource $resource = '' ) : boolean | ||
$row | integer | The row you want to move the pointer to. $row starts at 0. $row should be a value in the range from 0 to {@link returned_rows} @param resource $resource (Optional) Resource to fetch. If not specified, the resource returned by the last run query is used. @since 1.1.0 @return boolean Returns TRUE on success or FALSE on failure. |
$resource | resource | |
return | boolean |
$db->select(
'column1, column2',
'table',
'criteria = ?',
array($criteria)
);
or
$db->select(
array('column1', 'column2'),
'table',
'criteria = ?',
array($criteria)
);
or
$db->select(
'*',
'table',
'criteria = ?',
array($criteria)
);
public select ( mixed $columns, string $table, string $where = '', array $replacements = '', string $order = '', mixed $limit = '', mixed $cache = false, boolean $calc_rows = false, boolean $highlight = false ) : mixed | ||
$columns | mixed | 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. @param 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 {@link query()} method. @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword). Default is "" (an empty string). @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then concatenated with the other elements from the array - useful when using WHERE column IN (?) conditions. See second example {@link query here}. Default is "" (an empty string). @param string $order (Optional) A MySQL ORDER BY clause (without the ORDER BY keyword). Default is "" (an empty string). @param mixed $limit (Optional) A MySQL LIMIT clause (without the LIMIT keyword). Default is "" (an empty string). @param 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 {@link caching_method} property. Default is FALSE. @param 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 {@link 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. {@link http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows Here's how} Default is FALSE. @param 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. @since 2.0 @return mixed 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! |
$table | string | |
$where | string | |
$replacements | array | |
$order | string | |
$limit | mixed | |
$cache | mixed | |
$calc_rows | boolean | |
$highlight | boolean | |
return | mixed |
public set_charset ( string $charset = 'utf8', string $collation = 'utf8_general_ci' ) : void | ||
$charset | string | (Optional) The character set to be used by the database. Default is 'utf8'. See the {@link http://dev.mysql.com/doc/refman/5.1/en/charset-charsets.html list of possible values} @param string $collation (Optional) The collation to be used by the database. Default is 'utf8_general_ci'. See the {@link http://dev.mysql.com/doc/refman/5.1/en/charset-charsets.html list of possible values} @since 2.0 @return void |
$collation | string | |
return | void |
public show_debug_console ( boolean $return = false ) : void | ||
$return | boolean | (Optional) If set to TRUE, the output will be returned instead of being printed to the screen. Default is FALSE. @return void |
return | void |
checks whether table "users" exists
table_exists('users');
public table_exists ( string $table ) : boolean | ||
$table | string | The name of the table to check if it exists in the database. @since 2.3 @return boolean Returns TRUE if table given as argument exists in the database or FALSE if not. |
return | boolean |
start transactions
$db->transaction_start();
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
$db->transaction_complete();
public transaction_complete ( ) : boolean | ||
return | boolean |
start transactions
$db->transaction_start();
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
$db->transaction_complete();
public transaction_start ( boolean $test_only = false ) : boolean | ||
$test_only | boolean | (Optional) Starts the transaction system in "test mode" causing the queries to be rolled back (when {@link transaction_complete()} is called) - even if all queries are valid. Default is FALSE. @since 2.1 @return boolean Returns TRUE on success or FALSE on error. |
return | boolean |
$db->truncate('table');
public truncate ( string $table, boolean $highlight = false ) : boolean | ||
$table | string | Table to truncate. @param 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. @since 1.0.9 @return boolean Returns TRUE on success of FALSE on error. |
$highlight | boolean | |
return | boolean |
notice that we're using a MySQL function as a value
$db->update(
'table',
array(
'column1' => 'value1',
'column2' => 'value2',
'date_updated' => 'NOW()',
),
'criteria = ?',
array($criteria)
);
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 we have to escape the value ourselves
$db->update(
'table',
array(
'column1' => 'TRIM(UCASE("' . $db->escape($value1) . '"))',
'column2' => 'value2',
'date_updated' => 'NOW()',
),
'criteria = ?',
array($criteria)
);
public update ( string $table, array $columns, string $where = '', array $replacements = '', boolean $highlight = false ) : boolean | ||
$table | string | Table in which to update.
@param 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
{@link 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:
$db->update(
'table',
array(
'column' => 'INC(?)',
),
'criteria = ?',
array(
$value,
$criteria
)
);
...is equivalent to
$db->query('UPDATE table SET column = colum + ? WHERE criteria = ?', array($value, $criteria));
You may also use any of {@link http://www.techonthenet.com/mysql/functions/ 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 {@link escape} the values yourself!
@param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
Default is "" (an empty string).
@param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
marks) in $where. Each item will be automatically {@link 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 {@link escape()}-ed and then
concatenated with the other elements from the array - useful when using WHERE
column IN (?) conditions. See second example {@link query here}.
Default is "" (an empty string).
@param 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.
@since 1.0.9
@return boolean Returns TRUE on success of FALSE on error |
$columns | array | |
$where | string | |
$replacements | array | |
$highlight | boolean | |
return | boolean |
update some columns in a table
$db->update('table', array(
'column_1' => 'value 1',
'column_2' => 'value 2',
), 'id = ?', array($id));
print the number of affected rows
echo $db->affected_rows;
public int $affected_rows | ||
return | integer |
public string $cache_path | ||
return | string |
the host where memcache is listening for connections
$db->memcache_host = 'localhost';
the port where memcache is listening for connections
$db->memcache_port = 11211;
for this to work, PHP needs to be configured with --with-zlib[=dir] !
set it to FALSE otherwise
$db->memcache_compressed = true;
cache queries using the memcache server
$db->caching_method = 'memcache';
only now it is the time to connect
$db->connect(...)
Caching is done on a per-query basis by setting the "cache" argument when calling some of the library's
methods like {@link query()}, {@link select()}, {@link dcount()}, {@link dlookup()}, {@link dmax()} and {@link dsum()}!
Default is "disk". public string $caching_method | ||
return | string |
show 50 records
$db->console_show_records(50);
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:
set PHP's memory limit to 20 MB
ini_set('memory_limit','20M');
Default is 20. public int $console_show_records | ||
return | integer |
disable the generation of debugging information
$db->debug = false;
Default is TRUE. public bool $debug | ||
return | boolean |
show the debugging console only to specific IPs
$db->debugger_ip = array('xxx.xxx.xxx.xxx', 'yyy.yyy.yyy.yyy');
Default is an empty array. public array $debugger_ip | ||
return | array |
public bool $disable_warnings | ||
return | boolean |
let's assume that "table" has 100 rows
but we're only selecting the first 10 of those
the last argument of the method tells the library
to get the total number of records in the table
$db->query('
SELECT
*
FROM
table
WHERE
something = ?
LIMIT
10
', array($somevalue), false, true);
prints "10"
as this is the number of records
returned by the query
echo $db->returned_rows;
prints "100"
because we set the "calc_rows" argument of the
"query" method to TRUE
echo $db->found_rows;
public int $found_rows | ||
return | integer |
don't stop execution for unsuccessful queries (if possible)
$db->halt_on_errors = false;
Default is TRUE. public bool $halt_on_errors | ||
return | boolean |
public string $log_path | ||
return | string |
consider queries running for more than 5 seconds as slow and send email
$db->max_query_time = 5;
Default is 10. public int $max_query_time | ||
return | integer |
public bool $memcache_compressed | ||
return | boolean |
public mixed $memcache_host | ||
return | mixed |
public string $memcache_key_prefix | ||
return | string |
public mixed $memcache_port | ||
return | mixed |
public bool $minimize_console | ||
return | boolean |
the email address where to send an email when there are slow queries
$db->notification_address = '[email protected]';
public string $notification_address | ||
return | string |
set a domain name so that you'll know where the email comes from
$db->notifier_domain = 'yourdomain.com';
public string $notifier_domain | ||
return | string |
public string $resource_path | ||
return | string |
$db->query('
SELECT
*
FROM
table
WHERE
something = ?
LIMIT
10
', array($somevalue));
prints "10"
as this is the number of records
returned by the query
echo $db->returned_rows;
public int $returned_rows | ||
return | integer |