DHTMLSQL

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

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

Visit http://dhtml.github.io/dhtmlsql for documentation.

Visit http://dhtml.github.io/dhtmlsql/api for complete API documentation.

For more resources visit http://github.com/dhtml

author Anthony Ogundipe a.k.a dhtml @author url http://www.dhtmlextreme.com , http://www.africoders.com @version 1.0.0 (last revision: January 01, 2016) @copyright (c) 2016 Anthony Ogundipe @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE @package DHTMLSQL
package Default

 Methods

___call

__call($name, $arguments) : mixed

Whenever you call a method that does not exist in this library This routine is executed.

If the method called can be found in mysqli, then it falls back to that Otherwise, if the method can be found in the last result object, then a fallback to this is executed Otherwise null is returned

An example of using prepared statements is shown below: $stmt = $db->prepare("INSERT INTO users (first, last) VALUES (?, ?)"); $stmt->bind_param("ss", $first, $last); // set parameters and execute $first = "John"; $last = "Doe"; $stmt->execute();

prepare and bind_param are standard MySQLi methods but are not defined in this library but as a result of this fallback technique, such methods and others like fetch_object, fetch_count etc will work

Parameters

$name

$arguments

Returns

mixed

__construct

__construct() 

Class constructor

__destruct

__destruct() 

Frees the memory associated with the last result.

access private

__get

__get($name) : mixed

Whenever you attempt to retrieve a property that does not exist in this library This routine is executed.

If the property belongs to the result object, it shall be retrieved otherwise, if it belongs to the connection object, it shall be subsequently retrieved otherwise null shall be returned

An example is getting the host information: echo $db->host_info;

As well as retrieving values like insert_id, affected_rows echo $db->insert_id; echo $db->affected_rows;

Parameters

$name

Returns

mixed

__log

_log(array $data) 

Enables processing of database errors

The following code is used internally when database connection does not exist if (!$this->connected()) { $this->_log(array( 'query' => $sql, 'error' => 'No active database connection' )); } A full error error message will be produced internally similar to: Error: select * from users => No active database connection

The internally generated error message is passed on to the internal halt function

Parameters

$data

array

An associative array with 2 keys: query and error

@return void

affected_rows

affected_rows() : integer

Get number of affected rows in previous MySQL operation

Returns

integernumber of affected rows otherwise -1 if last result fails

connect

connect(mixed $host = null, $username = null, $password = null, $dbname = null, $port = null, $socket = null
Static

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

// create the database object $db = DHTMLSQL::connect();

Parameters

$host

mixed

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

                         Prepending host by p: opens a persistent connection.

                        If the host is an already existing mysqli connection, then it shall be re-used

@param string $username (Optional) The user name used for authentication when connecting to the MySQL server.

@param string $password (Optional) The password used for authentication when connecting to the MySQL server.

@param string $dbname (Optional) 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.

@return object DHTMLSQL object is returned

$username

$password

$dbname

$port

$socket

connect_error

connect_error() : string

Retrieves connection error after calling the connect method

echo $db->connect_error();

Returns

stringsql connection error in case of unsuccessful connection otherwise empty string

connected

connected() : boolean

Confirms if a successful connection has been made to the database It is meant to be called after the connect method

if(!$db->connected()) { exit("Unable to connect to database. Reason: ".$db->connect_error()); }

Returns

booleanreturns true if a successful connection has been made otherwise returns false

db_prefix_tables

db_prefix_tables(string $stmt, $table_prefix) 

Allows you prefix your table names in curly braces in an sql statement

Parameters

$stmt

string

sql statements to be processed

@param string $table_prefix prefix to add for names of tables

$db->db_prefixtables("select * from {users} where 1",'ow');

select * from ow_users where 1

@return string Returns sql statement with table names (in curly braces) prefixed

$table_prefix

del

del(string $table, $where = '', $replacements = ''

Shorthand for deleting some or all items in a table.

$db->del('users','id>?',array(16));

Parameters

$table

string

Table to delete from.

@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).

@return mixed On success, returns a resource or FALSE on error.

$where

$replacements

dlookup

dlookup(string $column, $table, $where = '', $replacements = ''

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 you will stay clear of SQL injections $result = $db->dlookup('name, surname, age', 'users', 'gender = ?', array($gender));

Parameters

$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).

@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

$where

$replacements

escape

escape(string $string) 

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

This method also encloses given string in single quotes!

Works even if magic_quotes is ON.

// 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));

Parameters

$string

string

String to be quoted and escaped.

@return string Returns the quoted string with special characters escaped in order to prevent SQL injections. .

export

export(mixed $tables = '*', $file = null

Allows you to export entire database or specified tables to file or trigger download via browser

saves entire database to output.sql $db->export('*','output.sql');

saves a single table to output.sql $db->export(array('users'),'output.sql');

saves 2 tables to output.sql $db->export(array('users','country'),'output.sql');

downloads entire database via browser $db->export('*');

downloads a single table via browser $db->export(array('users'));

downloads 2 tables via browser $db->export(array('users','country'));

Parameters

$tables

mixed

(Optional) An array containing tables for export, or A string containing '*' to process all tables in the database (default)

@param string $file (Optional) The file to backup database to.

                             If not specified, a browser download will be triggered.

@return void

$file

fetch_assoc_all

fetch_assoc_all() : 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.

// 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();

Returns

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

fetch_sql

fetch_sql() : string

Gets the last SQL statement executed

$db->query("show tables"); echo $db->fetch_sql();

Returns

stringthe last sql statement executed

fetch_table

fetch_table(string $t) 

Generates an export of a table

// saves entire database to output.sql $db->fetch_table('users');

Parameters

$t

string

name of table to export

@return string the entire export sql statements for the table

get

get() : object
Static

Statical way of instantiating the class

$db=DHTMLSQL::get();

Since it is chainable, so we can also use it to connect to the database $db=DHTMLSQL::get()->connect('localhost','admin','pass','dbtest');

Returns

objectDHTMLSQL class object is returned

__halt

halt(string $message) 

This is a routine meant to handle MySQLi query errors If you try to select data from a table that does not exist An error message explaining the problem will be passed to _log and finally to halt halt acts in various ways depending on certain conditions

  1. If you have any halt function defined in the general scope, that function will be called with a message parameter
  2. If the print_error configuration variable is true (default), then the error will be printed on screen
    1. If halt_on_error configuration variable is set to true (default) then execution of the script is stopped

Parameters

$message

string

Error message explaining why execution should be stopped

@return void

implode

implode(array $pieces) 

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

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

$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) . ') ');

$db->query(' SELECT column FROM table WHERE column IN (?) ', array($array));

Parameters

$pieces

array

An array with items to be "glued" together

@return string Returns the string representation of all the array elements in the same order, escaped and with commas between each element.

import

import(string $path) 

Allows you to parse an entire sql file

// downloads a single table via browser $db->import("database.sql");

Parameters

$path

string

The file containing the sql query.

@return boolean True for success, false for failure

insert

insert(string $table, $columns, $ignore = false

Shorthand for INSERT queries.

When using this method column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically \escape()d in order to prevent SQL injections.

$db->insert( 'table', array( 'column1' => 'value1', 'column2' => 'value2', ));

Parameters

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

@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. If $ignore is an array, then insert_update method is triggered automatically

                             For more information see {@link http://dev.mysql.com/doc/refman/5.5/en/insert.html MySQL's INSERT IGNORE syntax}.

                             Default is FALSE.

@return boolean Returns TRUE on success of FALSE on error.

$columns

$ignore

insert_bulk

insert_bulk(string $table, $columns, $data, $ignore = false

Shorthand for inserting multiple rows in a single query.

When using this method column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically \escape()d in order to prevent SQL injections.

$db->insert_bulk( 'table', array('column1', 'column2'), array( array('value1', 'value2'), array('value3', 'value4'), array('value5', 'value6'), array('value7', 'value8'), array('value9', 'value10') ) ));

Parameters

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

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

@return boolean Returns TRUE on success of FALSE on error.

$columns

$data

$ignore

insert_id

insert_id() : integer

Get the ID generated from the previous INSERT operation

Returns

integerreturns generated ID otherwise 0 (if no ID was generated or autoincrement was not set)

insert_update

insert_update(string $table, $columns, $update = array()

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

// 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. $db->insert_update( 'table', array( 'article_id' => $article_id, 'votes' => 0, ), array( 'votes' => 'INC(1)', ) );

Parameters

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

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

                             Default is an empty array.

@return boolean Returns TRUE on success of FALSE on error.

$columns

$update

load

load() 
Static

Static constructor of class You can instantiate the class object in a dynamic manner via $db=new DHTMLSQL(); You can instantiate the class object in a static manner via $db=DHTMLSQL::load();

Gets the number of rows returned in a select statement

num_rows() : integer

$db->query("show tables"); echo $db->num_rows();

Returns

integerthe number of rows returned otherwise 0

optimize

optimize() : void

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

// optimize all tables in the database $db->optimize();

pquery

pquery(string $sql, $items_per_page = 10, $pager_variable = 'page'

This function will execute an sql query in pagination mode

Parameters

$sql

string

a normal sql query without limits e.g. select first,last from Employees

@param string $items_per_page the number of results to list per page

@param string $pager_variable_item the pagination variable to use in the browser

If the property belongs to the result object, it shall be retrieved otherwise, if it belongs to the connection object, it shall be subsequently retrieved otherwise null shall be returned

An example is shown below: $db->pquery('select * from country',5,'page');

while($row=$db->fetch_assoc()) { var_dump($row); }

if($db->pager->num_rows>0) { echo $db->pager->show_navigation(); }

@return boolean True for success, false for failure

$items_per_page

$pager_variable

pquery_all

pquery_all(string $sql) 

This function will execute an sql query in pagination mode and render all possible results

Parameters

$sql

string

a normal sql query without limits e.g. select first,last from Employees

If the property belongs to the result object, it shall be retrieved otherwise, if it belongs to the connection object, it shall be subsequently retrieved otherwise null shall be returned

An example is shown below: $db->pquery_all('select * from country');

while($row=$db->fetch_assoc()) { var_dump($row); }

@return boolean True for success, false for failure

preview

preview($mode) : void

Turns on and off the preview mode. When preview mode is on, SQL statements are displayed on screen rather than executed

$db->preview(true); $db->query("show tables"); echo $db->num_rows();

Parameters

$mode

query

query(string $sql, $replacements = ''

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.

// 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)));

Parameters

$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).

@return mixed On success, returns a resource or FALSE on error.

$replacements

replace

replace(string $table, $columns) 

Shorthand for REPLACE queries.

When using this method column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically \escape()d in order to prevent SQL injections.

$db->replace( 'table', array( 'column1' => 'value1', 'column2' => 'value2', ));

Parameters

$table

string

Table in which to replace into.

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

@return boolean Returns TRUE on success of FALSE on error.

$columns

reset_result

reset_result() 

Reset the internal pointer back to zero

$db->query("show tables"); while($row=$db->fetch_assoc()) { var_dump($row); }

//we reset the result pointer here

$db->reset_result();

//so that we can loop through the results again

while($row=$db->fetch_assoc()) { var_dump($row); }

reset_session_logger

reset_session_logger() : boolean

Empties the session_log output file

$db->session_logger="sql.log"; $db->reset_session_logger();

Returns

booleantrue if successful (or file does not exist), false if no output file was specified

select

select(mixed $columns, $table, $where = '', $replacements = '', $order = '', $limit = ''

Shorthand for simple SELECT queries.

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

When using this method, column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically \escape()d in order to prevent SQL injections.

$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) );

Parameters

$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).

@return mixed On success, returns a resource or FALSE on error.

$table

$where

$replacements

$order

$limit

set_charset

set_charset(string $charset = 'utf8', $collation = 'utf8_general_ci'

Sets MySQL character set and collation.

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

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

Warnings can be disabled by setting the \disable_warnings property.

Parameters

$charset

string

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

                         Default is 'utf8'.

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

@param string $collation (Optional) The collation to be used by the database.

                         Default is 'utf8_general_ci'.

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

@return void

$collation

show_navigation

show_navigation() : string

This function will return the html code for the navigation interface

Returns

stringhtml code for pagination area

table_exists

table_exists(string $table) 

Checks whether a table exists in the current database.

// checks whether table "users" exists table_exists('users');

Parameters

$table

string

The name of the table to check if it exists in the database.

@return boolean Returns TRUE if table given as argument exists in the database or FALSE if not.

truncate

truncate(string $table) 

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.

$db->truncate('table');

Parameters

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

@return boolean Returns TRUE on success of FALSE on error.

update

update(string $table, $columns, $where = '', $replacements = ''

Shorthand for UPDATE queries.

When using this method column names will be enclosed in grave accents " ` " (thus, allowing seamless usage of reserved words as column names) and values will be automatically \escape()d in order to prevent SQL injections.

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

$db->update( 'table', array( 'column1' => 'value1', 'column2' => 'value2', ), 'criteria = ?', array($criteria) );

Parameters

$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));
                             

@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).

@return boolean Returns TRUE on success of FALSE on error

$columns

$where

$replacements

version

version() : string

Retrieves the current version information of library

Returns

string

_build_columns

_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 \escape() value.

access private @return string

Parameters

$columns

_build_sql

_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 \escape() value.

It will also take care of particular cases where the INC keyword is used in the values, where the INC keyword is used with a parameter marker ("?", question mark) or where a value is a single question mark - which throws an error message.

This method may also alter the original variable given as argument, as it is passed by reference!

access private

Parameters

$columns

_connect

_connect(mixed $host = null, $username = null, $password = null, $dbname = null, $port = null, $socket = null

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

// create the database object $db = new DHTMLSQL();

$db->connect('host', 'username', 'password', 'database');

Parameters

$host

mixed

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

                         Prepending host by p: opens a persistent connection.

                        If the host is an already existing mysqli connection, then it shall be re-used

@param string $username (Optional) The user name used for authentication when connecting to the MySQL server.

@param string $password (Optional) The password used for authentication when connecting to the MySQL server.

@param string $dbname (Optional) 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.

@return object DHTMLSQL object is returned

$username

$password

$dbname

$port

$socket

is_result

_is_result($value) 

Checks is a value is a valid result set obtained from a query against the database

access private

Parameters

$value

session_log

session_log(string $log = ''

Enables internal logging of SQL queries to file

$db->session_logger="sql.log"; $db->session_logging=true; $db->query("select 1");

Parameters

$log

string

(Optional) The string to be logged

@access private

@return void

 Properties

 

halt_on_error

$halt_on_error : boolean

Default

true

Determines if application should halt whenever there is a database error

Default is TRUE.

 

last_result

$last_result : resource

Default

null

Last database result resource

Default is null.

 

print_error

$print_error : boolean

Default

true

Prints error log to screen whenever an error occurs while executing a statement

Default is TRUE.

 

returned_rows

$returned_rows : integer

Default

Number of rows returned by query

Default is 0.

 

session_logger

$session_logger : string

Default

''

Configures the path where database queries will be logged if session_logging is set to true It can be a path that is writeable If this is not specified and session_logging=true then dbase.log will be used for logging by default

Default is an empty string.

 

session_logging

$session_logging : boolean

Default

false

Configures library database query logging When set to true, each query executed is logged to dbase.log

Default is FALSE.

 

Instance

$Instance 

Default

Static

Static library class

access private @var resource
 

connect_error

$connect_error : string

Default

""

Logs the connection error if there is one

Default is an empty string.

 

connection

$connection 

Default

null

MySQL link identifier.

access private @var object
 

last_sql

$last_sql 

Default

""

Last sql statement issues internally

Default is an empty string.

access private @var string
 

preview_mode

$preview_mode : boolean

Default

false

Configures the special preview mode When set to true, each query meant to be executed will be printed and on screen and not executed This is useful in development mode for testing the library

Default is FALSE.

 

result

$result 

Default

MySQL result set.

access private @var object
 

version

$version 

Default

"1.0.0"

Current library version

access private @var string