PHP MySQL Wrapper Class
PHP MySQL Wrapper Class
USER MANUAL
1. Introduction 5
2. Chapter 1 - Connect to a MySQL server 7
2.1 Connectivity settings .......................................................................................................... 8
2.2 Connect to a given MySQL server ...................................................................................... 8
2.3 Connection examples .......................................................................................................... 8
2.4 Connection example multi host, db manipulation .......................................................... 9
2.5 Set the connection character set encoding ...................................................................... 9
8. Chapter 7 - Transactions 37
9. Chapter 8 - String Search and Replace 39
10. Chapter 9 - Basic table operations 41
10.1 Basic Table operations ...................................................................................................... 42
10.2 Get table columns ............................................................................................................. 43
10.3 Get database size ............................................................................................................... 43
10.4 Next AutoIncrement ......................................................................................................... 43
10.5 Table revision .................................................................................................................... 44
Index 0
1 Introduction
It can:
· Connectivity settings
· Connect to a given MySQL server
· Connection examples
· Connection example multi host, db manipulation
· Set the connection character set encoding
Connectivity settings
// Connect
$db->connect();
//
// ... do queries
//
// Close connection
$db->close();
Connection examples
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect 1
$db->connect();
//
// Connection 1 queries ...
//
// Close connection 1
$db->close();
// Connect 2
$db->connect(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
//
// Connection 2 queries ...
//
// Close connection 2
$db->close();
// Connection 3
$db->connect();
//
// Connection 3 queries
//
// Close connection 3
$db->close();
// Inst. 2
$db2 = MySQL_wrapper::getInstance('host2', MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect host 1
$db1->connect();
// Connect host 2
$db2->connect();
//
// ... do queries of cennection 1 or connection 2
//
Example 1
// Connect
$db->connect();
// Set charset
$db->charset = 'utf8';;
// Close connection
$db->close();
Example 2
// Connect
$db->connect();
// Set charset
$db->setCharset('utf8');
// Close connection
$db->close();
// Connect to host
$db->connect();
// MySQL query
$db->query('SELECT * FROM `table`');
// Escape string
$var = '\'';
// Do query
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '{$db->escape($var)}';");
// Param to be escaped
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@1%' OR `surname` LIKE
'%@1%';", 'rado');
// Params as args
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@1%' AND `surname` LIKE
'%@2%' OR id = @3;", 'rado', 'janjic', 3 /* , ... */);
// Array of params
$params = array();
$params['id'] = 1;
$params['name'] = 'rado';
$params['lname'] = 'janjic';
$params['limit'] = 5;
// Exec query
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@name%' AND `surname`
LIKE '%@lname%' OR `id` = @id LIMIT @limit;", $params);
// Close connection
$db->close();
// Connect
$db->connect();
$name = 'Radovan';
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something
// print_r($row);
// ...
}
// Close connection
$db->close();
// Connect
$db->connect();
// Print data
print_r($data);
// Close connection
$db->close();
// Connect
$db->connect();
// Print array
print_r($array);
// Print array
print_r($array);
// Close connection
$db->close();
Multi results
// Connect to host
$db->connect();
// Result 1
$r1 = $db->query('SELECT * FROM `table`');
// Result 2
$r2 = $db->query('SELECT * FROM `table` LIMIT 2');
// Result 1 data
if ($db->numRows($r1)) {
while ($row = $db->fetchArray($r1)) {
// Print rows
print_r($row);
}
}
// Result 2 data
if ($db->numRows($r2)) {
while ($row = $db->fetchArray($r2)) {
// Print rows
print_r($row);
}
}
// Free relust 1
$db->freeResult($r1);
// Free relust 2
$db->freeResult($r2);
// Close connection
$db->close();
// Connect to host
$db->connect();
// Do query
$db->query('SELECT * FROM `table`');
$cols = $db->numFields();
$rows = $db->numRows();
// ...
echo "Cols: {$cols}, Rows: {$rows}";
// Close connection
$db->close();
Count rows
// Connect to host
$db->connect();
// Count all
$count = $db->countRows('table');
// ...
echo "Count all: {$count}, Count today: {$count2}";
// More info
/** Retrieves the number of rows from table based on certain conditions.
* @param string $table - Table name
* @param string $where - WHERE Clause
* @return integer or false
*
* function countRows($table, $where = NULL);
*/
// Close connection
$db->close();
Execute UPDATE or INSERT queries from parameters that define the tables,
fields, field values and conditions
· Array to insert
· Multiple array to insert
· Array to update
· Multiple array to update
Array to insert
// Connect to host
$db->connect();
// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = 'rade@it-radionica.com';
// reserved values 'null', 'now()', 'curtime()', 'localtime()', 'localtime',
'utc_date()', 'utc_time()', 'utc_timestamp()'
$data['date'] = 'now()';
// More options
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';
* @param boolean $ingore - INSERT IGNORE (row won't actually be inserted if
it results in a duplicate key)
* @param string $duplicateupdate - ON DUPLICATE KEY UPDATE (The ON
DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by
commas.)
* @return insert id or false
*
* function arrayToInsert($table, $data, $ignore = FALSE, $duplicateupdate =
NULL);
*/
// Close connection
$db->close();
// Connect to host
$db->connect();
// Array data
// [fealdname] = feald value
$data = array();
// Data set 1
$data[] = array(
'firstname' => 'foo',
'surname' => 'bar',
'email' => 'hi@radovanjanjic.com',
'date' => 'now()'
);
// Data set 2
$data[] = array(
'firstname' => 'baz',
'surname' => 'qux',
'email' => 'hi@radovanjanjic.com',
'date' => 'now()'
);
// Close connection
$db->close();
Array to update
// Connect to host
$db->connect();
// Array data
// More options
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';
* @param string $where - MySQL WHERE Clause
* @param integer $limit - Limit offset
* @param resource $link - link identifier
* @return number of updated rows or false
*
* function arrayToUpdate($table, $data, $where = NULL, $limit = 0, $link = 0);
*/
// Close connection
$db->close();
// Connect to host
$db->connect();
// Array data
// [fealdname] = feald value
$data = array();
// Data set 1
$data[] = array(
// Condition
'id' => 1, // One of the fields has to be primary or unique key in order to
update
// Data to update
'firstname' => 'foooo',
'surname' => 'barrr'
// ...
);
// Data set 2
$data[] = array(
// Condition
'id' => 2, // One of the fields has to be primary or unique key in order to
update
// Data to update
'firstname' => 'bazzz',
'surname' => 'quxxx'
// ...
);
// Close connection
$db->close();
Delete row(s)
// Connect to host
$db->connect();
// Delete row
$db->deleteRow('table', "`id` = {$insert_id}");
if ($db->affected > 0) {
echo "Deleted: {$db->affected} row(s).";
}
// More options
/** Delete row(s) from table based on certain conditions.
* @param string $table - Table name
* @param string $where - WHERE Clause
* @param integer $limit - Limit offset
* @param resource $link - link identifier
* @return number of deleted rows or false
*
* function deleteRow($table, $where = NULL, $limit = 0, $link = 0);
*/
// Close connection
$db->close();
// Connect
$db->connect();
// More options
/** Export table data to CSV file.
* @param string $table - Table name
* @param string $file - CSV File path
* @param mixed $columns - SQL ( * or column names or array with
column names)
* @param string $where - MySQL WHERE Clause
* @param integer $limit - Limit offset
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param string $newLine - New line detelimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return number of inserted rows or false
*
// Close connection
$db->close();
// Connect
$db->connect();
// Example 2
$path = $db->query2CSV('select * from `table` limit 2,2', 'test_files/test-
query2csv.csv');
// Close connection
$db->close();
// Connect
$db->connect();
// Table to CSV
$db->exportTable2CSV('table', 'test_files/test-1.txt');
// Query to CSV
$path = $db->query2CSV('select * from `table` limit 10', 'test_files/test-
query2csv.csv');
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
// Connect
$db->connect();
// More options
/** Imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
// Connect to host
$db->connect();
$db->dropTable('csv_to_table_test');
$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');
$db->dropTable('csv_to_table_test_no_column_names');
$db->createTableFromCSV('test_files/countrylist1.csv',
'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate',
'\r\n');
/** Create table from CSV file and imports CSV data to Table with possibility to
update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg
date format or increment (SQL format only @FIELD is variable with content of that
field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%
Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or
generate) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: \n)
* @return number of inserted rows or false
*
* function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"',
$escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine
= '\r\n');
*/
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
8 Chapter 7 - Transactions
Transactions
// Connect
$db->connect();
// Queries
$queries = array();
$queries[] = 'SELECT ...';
$queries[] = 'INSERT ...';
$queries[] = 'DELETE ...';
$queries[] = '...';
// Do Transaction
$db->transaction($queries);
// Close connection
$db->close();
// Connect to host
$db->connect();
// Rename table
$db->renameTable(array('table_copy' => 'table_copy3'));
// Close connection
$db->close();
// Connect
$db->connect();
print_r($array);
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
// Connect to host
$db->connect();
// Close connection
$db->close();
Table revision
// Connect
$db->connect();
// Close connection
$db->close();
Logging / debug
· Logging errors
· Logging queries
· E-mail on error / die on error
· Errors backtrace and debug
· Display error example
Logging errors
// Connect to host
$db->connect();
// Log file
$db->logFilePath = 'log-mysql.txt';
// Close connection
$db->close();
Logging queries
// Connect to host
$db->connect();
// Log file
$db->logFilePath = 'log-mysql.txt';
// Close connection
$db->close();
// Connect
$db->connect();
// Die on errors
$db->dieOnError = TRUE;
// Array of emails
$db->emailErrorsTo = array('rade@it-radionica.com');
// Do first query
$db->query("select * from asdf");
// This one will not be executed if first query have error and dieOnError is TRUE
$db->query("select * from asdf2");
// Close connection
$db->close();
// Connect to host
$db->connect();
// Close connection
$db->close();
// Connect
$db->connect();
// Close connection
$db->close();
Explain output:
+-------------------------------------------------------------------------------------
-+
| Explain MySQL Query
|
+----+-------------+-------+------+---------------+-----+---------+-----+------
+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
|
+----+-------------+-------+------+---------------+-----+---------+-----+------
+-------+
Describe output:
+------------------------------------------------------------------+
| test |
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | | auto_increment |
| firstname | varchar(100) | NO | | | |
| surname | varchar(100) | NO | | | |
+-----------+--------------+------+-----+---------+----------------+
/** Link
* @var resource
*/
public $link = 0;
/** Query
* @var resource
*/
public $query = 0;
/** REGEX
* @var array
*/
private $REGEX = array('LIMIT' => '/limit[\s]+([\d]+[\s]*,[\s]*[\d]+[\s]*|[\d]
+[\s]*)$/i', 'COLUMN' => '/^[a-z0-9_\-\s]+$/i');
/** Connect
* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
* @param boolean $newLink - New link
* @return boolean
*/
public function connect($server = NULL, $username = NULL, $password = NULL,
$database = NULL, $newLink = FALSE) {
if ($server !== NULL && $username !== NULL && $database !== NULL) {
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
if ($this->extension == 'mysql') {
$this->link = @mysql_connect($this->server, $this->username, $this-
>password, $newLink) or $this->error("Couldn't connect to server: {$this-
>server}.");
if ($this->link) {
$this->setCharset();
@mysql_select_db($this->database, $this->link) or $this-
>error("Could not open database: {$this->database}.");
return TRUE;
} else {
return FALSE;
}
} elseif ($this->extension == 'mysqli') {
$this->link = mysqli_connect($this->server, $this->username, $this-
>password, $this->database);
// Check connection
if (mysqli_connect_errno($this->link)) {
$this->error("Failed to connect to MySQL: " .
mysqli_connect_error());
return FALSE;
} else {
$this->setCharset();
return TRUE;
}
}
}
/** Close Connection on the server that's associated with the specified link
(identifier).
* @param void
*/
public function close() {
$this->call('close') or $this->error("Connection close failed.");
}
/** Execute a unique query (multiple queries are not supported) to the
currently active database on the server that's associated with the specified link
(identifier).
* @param string $sql - MySQL Query
* @param mixed - array of params to be escaped or one param
* @param mixed - param
* @param mixed - ...
* @return resource or false
*/
public function query($sql) {
if (func_num_args() >= 2) {
$l = func_get_args();
unset($l[0]);
$p = array();
if (is_array($l[1])) {
$l = $l[1];
}
foreach ($l as $k => $v) {
$p['search'][] = "@{$k}";
if (preg_match('/^' . preg_quote($this->statementStart) . '/i',
$v)) {
$p['replace'][] = preg_replace('/^' . preg_quote($this-
>statementStart) . '/i', NULL, $v);
} else {
$p['replace'][] = $this->escape($v);
}
}
$sql = str_replace($p['search'], $p['replace'], $sql);
unset($l, $p);
}
if ($this->logQueries) {
$start = $this->getMicrotime();
}
$this->prevQuery = $sql;
$this->query = $this->call('query', $sql) or $this->error("Query fail: " .
$sql);
$this->affected = $this->call('affected_rows');
if ($this->query && $this->logQueries) {
$this->log('QUERY', "EXEC -> " . number_format($this->getMicrotime() -
$start, 8) . " -> " . $sql);
}
return $this->query ? $this->query : FALSE;
}
/** Returns an associative array that corresponds to the fetched row and moves
the internal data pointer ahead.
* @param resource $query - MySQL Query Result
* @return array or false
*/
public function fetchArray($query = 0) {
$this->query = $query ? $query : $this->query;
if ($this->query) {
return $this->call('fetch_assoc', $this->query);
} else {
$this->error("Invalid Query ID: {$this->query}. Records could not be
fetched.");
return FALSE;
}
}
if ($multirow) {
$c = implode('`, `', array_keys($data[0]));
$dat = array();
foreach ($data as &$val) {
foreach ($val as &$v) {
if (in_array(strtolower($v), $this->reserved)) {
$v = strtoupper($v);
} elseif (preg_match('/^' . preg_quote($this->statementStart) .
'/i', $v)) {
$v = preg_replace('/^' . preg_quote($this-
>statementStart) . '/i', NULL, $v);
} else {
$v = "'{$this->escape($v)}'";
}
}
$dat[] = "( " . implode(', ', $val) . " )";
}
$v = implode(', ', $dat);
} else {
$c = implode('`, `', array_keys($data));
foreach ($data as &$val) {
if (in_array(strtolower($val), $this->reserved)) {
$val = strtoupper($val);
} elseif (preg_match('/^' . preg_quote($this->statementStart) .
'/i', $val)) {
$val = preg_replace('/^' . preg_quote($this->statementStart) .
'/i', NULL, $val);
} else {
$val = "'{$this->escape($val)}'";
}
}
$v = "( " . implode(', ', $data) . " )";
}
return (!empty($data)) ? $this->query("INSERT" . ($ignore ? " IGNORE" :
NULL) . " INTO `{$table}` ( `{$c}` ) VALUES {$v}" . ($duplicateupdate ? " ON
DUPLICATE KEY UPDATE {$duplicateupdate}" : NULL) . ";") ? ($multirow ? TRUE :
$this->insertID()) : FALSE : FALSE;
}
/** Imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or
increment (SQL format only @FIELD is variable with content of that field in CSV
row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")',
'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or table) -
this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: auto detection use \n,
\r\n ...)
* @return number of inserted rows or false
*/
if (!empty($update)) {
if ($getColumnsFrom == 'table') {
$columns = $this->getColumns($table);
} elseif ($getColumnsFrom == 'file') {
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
$columns = explode($delimiter, str_replace($enclosure, NULL,
trim($line)));
foreach ($columns as $c) {
preg_match($this->REGEX['COLUMN'], $c) or $this->error("ERROR",
"Invalid Column Name: {$c} in CSV file: {$file}. Data can not be loaded into table:
{$table}.");
}
}
$fields = array();
foreach ($update as $key => $val) $fields[] = "`{$key}` = {$val}";
$sql .= "SET " . implode(', ', $fields);
}
$sql .= ";";
return ($this->query($sql)) ? $this->affected : FALSE;
}
/** Imports (ON DUPLICATE KEY UPDATE) CSV data in Table with possibility to
update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
if ($getColumnsFrom == 'file') {
// Get first line of file
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
if (count($change) > 0) {
// Import to tmp
$this->importCSV2Table($file, $tmp_name, $delimiter, $enclosure, $escape,
$ignore, $update, $getColumnsFrom, $newLine);
// Copy data
$cols = array();
if ($getColumnsFrom == 'table') {
$columns = $this->getColumns($tmp_name);
}
return $i;
}
fclose($fh);
$file = realpath($file);
unlink($file);
*/
public function query2CSV($sql, $file, $delimiter = ',', $enclosure = '"',
$escape = '\\', $newLine = '\n', $showColumns = TRUE) {
// Without OUTFILE or as attachment
if ($this->attachment || !$this->mysqlOutFile) {
// Do query
$this->query($sql);
if ($this->affected > 0) {
$fh = fopen($this->attachment ? 'php://output' : $file, 'w') or
$this->error("ERROR", "Can't create CSV file: {$file}");
if ($fh) {
if ($this->attachment) {
// Send response headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' .
basename($file));
header('Pragma: no-cache');
header('Expires: 0');
$this->attachment = FALSE;
}
$header = FALSE;
while ($row = $this->fetchArray()) {
// CSV header / field names
if ($showColumns && !$header) {
fputcsv($fh, array_keys($row), $delimiter, $enclosure);
$header = TRUE;
}
fputcsv($fh, array_values($row), $delimiter, $enclosure);
}
fclose($fh);
return $this->affected;
} else {
$this->attachment = FALSE;
return FALSE;
}
} else {
$this->attachment = FALSE;
// No records
return 0;
}
}
$r = $this->query((preg_match($this->REGEX['LIMIT'], $sql)) ?
preg_replace($this->REGEX['LIMIT'], 'LIMIT 1;', $sql) : $sql . ' LIMIT 1;');
if ($r !== FALSE && $this->affected > 0) {
$columns = $this->fetchArray($r);
$this->freeResult($r);
$tableColumnsArr = array();
foreach ($columns as $k => $v) {
$tableColumnsArr[] = "'{$k}' AS `{$k}`";
}
$columnsSQL = "SELECT " . implode(', ', $tableColumnsArr);
} else {
// No results for this query
return 0;
}
}
// Final query
$sql = (($showColumns && isset($columnsSQL)) ? "SELECT * FROM ( ( " .
$columnsSQL . " ) UNION ALL ( {$sql} ) ) `a` " : "{$sql} ") .
"INTO OUTFILE '{$this->escape($file)}' " .
"FIELDS TERMINATED BY '{$delimiter}' " .
"OPTIONALLY ENCLOSED BY '{$enclosure}' " .
"ESCAPED BY '{$this->escape($escape)}' " .
"LINES TERMINATED BY '{$newLine}';";
return ($this->query($sql)) ? $file : FALSE;
}
// Do query
$r = $this->query($query);
// XML header
if ($saveToFile) {
fputs($fh, "<?xml version=\"1.0\" encoding=\"" . strtoupper($this-
>charset) . "\" ?>" . PHP_EOL . "<{$rootElementName}>" . PHP_EOL);
} else {
$xml = "<?xml version=\"1.0\" encoding=\"" . strtoupper($this-
>charset) . "\" ?>" . PHP_EOL;
$xml .= "<{$rootElementName}>" . PHP_EOL;
}
// Query rows
while ($row = $this->call('fetch_object', $r)) {
// Create the first child element
$record = "\t<{$childElementName}>" . PHP_EOL;
for ($i = 0; $i < $this->call('num_fields', $r); $i++) {
// Different methods of getting field name for mysql and mysqli
if ($this->extension == 'mysql') {
$fieldName = $this->call('field_name', $r, $i);
} elseif ($this->extension == 'mysqli') {
$colObj = $this->call('fetch_field_direct', $r, $i);
$fieldName = $colObj->name;
}
// The child will take the name of the result column name
$record .= "\t\t<{$fieldName}>";
// Set empty columns with NULL and escape XML entities
if (!empty($row->$fieldName)) {
$record .= htmlspecialchars($row->$fieldName, ENT_XML1);
} else {
$record .= NULL;
}
$record .= "</{$fieldName}>" . PHP_EOL;
}
$record .= "\t</{$childElementName}>" . PHP_EOL;
if ($saveToFile) {
fputs($fh, $record);
} else {
$xml .= $record;
}
}
// Output
if ($saveToFile) {
fputs($fh, "</{$rootElementName}>" . PHP_EOL);
fclose($fh);
return TRUE;
} else {
$xml .= "</{$rootElementName}>" . PHP_EOL;
return $xml;
}
}
/** Create table from CSV file and imports CSV data to Table with possibility
to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
}
$this->query("ALTER TABLE `{$table}` " . implode(', ', $change) .
";");
}
}
}
/** Retrieves the number of rows from table based on certain conditions.
* @param string $table - Table name
* @param string $where - WHERE Clause
* @return integer or false
*/
public function countRows($table, $where = NULL) {
$r = $this->query("SELECT COUNT( * ) AS count FROM `{$table}` " . ($where ?
" WHERE {$where}" : NULL) . ";");
if ($r !== FALSE) {
$row = $this->fetchArray($r);
$this->freeResult($r);
return $row['count'];
} else {
return FALSE;
}
}
/** Replace all occurrences of the search string with the replacement string in
MySQL Table Column(s).
* @param string $table - Table name or "*" to replace in whole db
* @param mixed $columns - Search & Replace affected Table columns. An array
may be used to designate multiple replacements.
* @param mixed $search - The value being searched for, otherwise known as the
needle. An array may be used to designate multiple needles.
* @param mixed $replace - The replacement value that replaces found search
values. An array may be used to designate multiple replacements.
* @param string $where - WHERE Clause
* @param integer $limit - Limit offset
* @return integer - Affected rows
*/
public function strReplace($table, $columns, $search, $replace, $where = NULL,
$limit = 0) {
// Replace in whole DB
if ($table == '*') {
if (!is_array($columns)) {
$stringColumns = $columns;
if ($stringColumns != '*') {
// Put columns into array
$columns = array();
if (preg_match($this->REGEX['COLUMN'], $stringColumns)) {
$columns[] = $stringColumns;
} else {
foreach (explode(',', $stringColumns) as $c) {
$columns[] = trim(str_replace(array("'", "`", "\""),
NULL, $c));
}
}
if (empty($columns)) {
return FALSE;
}
}
}
$q = $this->query(
"SELECT DISTINCT `table_name` AS `table`, GROUP_CONCAT(DISTINCT
`column_name` ORDER BY `column_name`) AS `columns` FROM
`information_schema`.`columns` " .
"WHERE (`data_type` LIKE '%char%' OR `data_type` LIKE '%text' OR
`data_type` LIKE '%binary')" . (($stringColumns != '*') ? " AND `column_name` IN('"
. implode("', '", $columns) . "')" : NULL) . " AND `table_schema` = '{$this-
>database}' " .
"GROUP BY `table_name` ORDER BY `table_name`;"
);
$affected = 0;
if ($this->affected > 0) {
while ($row = $this->fetchArray($q)) {
// Columns
if (!is_array($columns)) {
$stringColumns = $columns;
$columns = array();
if ($stringColumns == '*') {
$columns = $this->getColumns($table);
} elseif (preg_match($this->REGEX['COLUMN'], $stringColumns)) {
$columns[] = $stringColumns;
} else {
// Put columns into array if not *
$columns = array();
foreach (explode(',', $stringColumns) as $c) {
$columns[] = trim(str_replace(array("'", "`", "\""), NULL,
$c));
}
}
}
// Update
$update = array();
foreach ($columns as $col) {
if (is_array($search)) {
foreach ($search as $k => $s) {
$update[] = "`{$col}` = REPLACE(`{$col}`, '{$this-
>escape($s)}', '{$this->escape(is_array($replace) ? $replace[$k] : $replace)}')";
}
} else {
$update[] = "`{$col}` = REPLACE(`{$col}`, '{$this-
>escape($search)}', '{$this->escape($replace)}')";
}
}
$this->query("UPDATE `{$table}` SET " . implode(', ', $update) . ($where ?
" WHERE {$where}" : NULL) . ($limit ? " LIMIT {$limit}" : NULL) . ";");
return $this->affected;
}
/** Commit
* @param void
*/
public function commit() {
return $this->query("COMMIT;");
/** Rollback
* @param void
*/
public function rollback() {
return $this->query("ROLLBACK;");
}
/** Transaction
* @param array $qarr - Array with Queries
* @link http://dev.mysql.com/doc/refman/5.0/en/commit.html
*/
public function transaction($qarr = array()) {
$commit = TRUE;
$this->begin();
foreach ($qarr as $q) {
$this->query($q);
if ($this->affected == 0) $commit = FALSE;
}
if ($commit == FALSE) {
$this->rollback();
return FALSE;
} else {
$this->commit();
return TRUE;
}
}
if ($this->affected > 0) {
while ($row = $this->fetchArray()) {
$drop[] = "DROP INDEX `{$row['Key_name']}`";
}
$this->freeResult();
}
$this->query("ALTER TABLE `{$rev_table}` " . implode(', ', $drop) . ";");
$change = array();
// Add revision fields
$change['revision_timestamp'] = "ADD `revision_timestamp` TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP FIRST";
$change['revision_action'] = "ADD `revision_action` enum('INSERT',
'UPDATE', 'DELETE') DEFAULT NULL FIRST";
$change['revision_user'] = "ADD `revision_user` CHAR( 256 ) NOT NULL
FIRST";
$change['revision_id'] = "ADD `revision_id` INT NOT NULL AUTO_INCREMENT
FIRST";
// Add keys
$change[] = "ADD KEY (`revision_action`, `revision_timestamp`)";
$change[] = "ADD KEY `revision_timestamp` (`revision_timestamp`)";
$change[] = "ADD PRIMARY KEY `revision_id` (`revision_id`)";
// Alter revision table
$this->query("ALTER TABLE `{$rev_table}` " . implode(', ', $change) . ";");
$columns = $this->getColumns($table);
// Insert trigger
$this->query(
"CREATE TRIGGER `{$table}_revision_insert` AFTER INSERT ON `{$table}` "
.
"FOR EACH ROW " .
"BEGIN " .
"INSERT INTO `{$rev_table}` (`revision_action`,
`revision_timestamp`, `revision_user`, `" . implode('`, `', $columns) . "`) VALUES
('INSERT', NOW(), USER(), NEW.`" . implode('`, NEW.`', $columns) . "`); " .
"END;"
);
// Update trigger
$this->query(
"CREATE TRIGGER `{$table}_revision_update` AFTER UPDATE ON `{$table}` "
.
"FOR EACH ROW " .
"BEGIN " .
"INSERT INTO `{$rev_table}` (`revision_action`,
`revision_timestamp`, `revision_user`, `" . implode('`, `', $columns) . "`) VALUES
('UPDATE', NOW(), USER(), NEW.`" . implode('`, NEW.`', $columns) . "`); " .
"END;"
);
// Delete trigger
$this->query(
"CREATE TRIGGER `{$table}_revision_delete` AFTER DELETE ON `{$table}` "
.
"FOR EACH ROW " .
"BEGIN " .
"INSERT INTO `{$rev_table}` (`revision_action`,
`revision_timestamp`, `revision_user`, `" . implode('`, `', $columns) . "`) VALUES
('DELETE', NOW(), USER(), OLD.`" . implode('`, OLD.`', $columns) . "`); " .
"END;"
);
// Update
$this->query(
"INSERT INTO `{$table}` (`" . implode('`, `', $columns) . "`) " .
"SELECT `" . implode('`, `', $columns) . "` " .
"FROM (" .
"SELECT `" . implode('`, `', $columns) . "` " .
"FROM `{$table}_revision` " .
"WHERE `revision_timestamp` <= STR_TO_DATE('" . date('Y-m-d
H:i:s', $time) . "', '%Y-%m-%d %H:%i:%s') " .
"ORDER BY `revision_timestamp` DESC" .
") AS `b`
WHERE `{$id_field}` NOT IN(" .
"SELECT `{$id_field}` " .
"FROM `{$table}_revision` " .
"WHERE `revision_timestamp` <= STR_TO_DATE('" . date('Y-m-d
H:i:s', $time) . "', '%Y-%m-%d %H:%i:%s') AND `revision_action` LIKE 'DELETE'" .
") GROUP BY `{$id_field}` " .
"ON DUPLICATE KEY UPDATE " . implode(', ', $cols) . ";"
);
}
// Header
if (!empty($title)) {
$ret[] = '+-' . str_pad(NULL, array_sum($p) + ((count($p) -1) * 3 ),
'-') . '-+';
$ret[] = '| ' . str_pad($title, array_sum($p) + ((count($p) -1) * 3 ),
' ', STR_PAD_BOTH) . ' |';
}
// Line
$r = array();
foreach ($p as $k) {
$r[] = str_pad(NULL, $k, '-');
}
$line = '+-' . implode($r, '-+-') . '-+';
// Before line
$ret[] = $line;
$header = 0;
// Table values
foreach ($data as $row) {
// Data row
$r = array();
foreach ($row as $key => $val) {
$r[] = str_pad($val, $p[$key], ' ', is_numeric($val) ? STR_PAD_LEFT
: STR_PAD_RIGHT);
}
$ret[] = '| ' . implode($r, ' | ') . ' |';
// Fields header
if ($header == 0) {
$ret[] = $line;
$header = 1;
}
}
// Last line
$ret[] = $line;
// Print table
echo '<pre>', htmlspecialchars(implode($ret, PHP_EOL), ENT_QUOTES),
'</pre>';
}
}
}
return FALSE;
}
}
13.2 Examples
<?php
/*
*/
require "PHP_MySQL_Wrapper.Class.php";
/*
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Close connection
$db->close();
*/
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 1
// Connection example
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
//
// ... do queries
//
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 2
// Connection example
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance();
// connect 1
$db->connect(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB); // You can use
connection info here as well
//
// Connection 1 queries
//
// Close connection 1
$db->close();
// Connect 2
$db->connect(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
//
// Connection 2 queries
//
// Close connection 2
$db->close();
// Connection 3 queries
//
// Close connection 3
$db->close();
// Example 3
// Connection example multi host, db manipulation
///////////////////////////////////////////////////////////////////////////////////
////////
// Host 1 instance
$db1 = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect host 1
$db1->connect();
// Connect host 2
$db2->connect();
//
// ... do queries of cennection 1 or connection 2
//
// Example 4
// Select example with fetch result
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// MySQL query
$db->query('SELECT * FROM `table`;');
// Escape string
$var = '\'';
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '{$db->escape($var)}';");
// Param to be escaped
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@1%' OR `surname` LIKE '%
@1%';", 'rado');
// Params as args
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@1%' AND `surname` LIKE
'%@2%' OR id = @3;", 'rado', 'janjic', 3 /* , ... */);
// Array of params
$params = array();
$params['id'] = 1;
$params['name'] = 'rado';
$params['lname'] = 'janjic';
$params['limit'] = 5;
$db->query("SELECT * FROM `table` WHERE `firstname` LIKE '@name%' AND `surname`
LIKE '%@lname%' OR `id` = @id LIMIT @limit;", $params);
$db->freeResult();
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 5
// Prepared statements (works only with MySQLi!)
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
$name = 'Radovan';
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something
// print_r($row);
// ...
}
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 5
// Faster select exmaple (fetch query to array)
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
echo "<hr /><strong>Example 5 (fetch query to array)</strong><pre>";
print_r($db->fetchQueryToArray('SELECT * FROM `table`'));
// Exmaple 6
// Multi results
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// Result 1
$r1 = $db->query('SELECT * FROM `table`');
// Result 2
$r2 = $db->query('SELECT * FROM `table` LIMIT 2');
// Result 1 data
echo "<hr /><strong>Example 6 (multi results)</strong><br> Result 1:<pre>";
if ($db->numRows($r1)) {
while ($row = $db->fetchArray($r1)) {
print_r($row);
}
}
echo "</pre>\nResult 2:\n<pre>";
// Result 2 data
if ($db->numRows($r2)) {
while ($row = $db->fetchArray($r2)) {
print_r($row);
}
}
echo "</pre>";
// Free relust 1
$db->freeResult($r1);
// Free relust 2
$db->freeResult($r2);
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 7
// Rows, Cols num
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
$cols = $db->numFields();
$rows = $db->numRows();
$db->freeResult();
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 8
// Count rows
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// Count all
$count = $db->countRows('table');
// Example 9
// Array to insert
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = 'rade@it-radionica.com';
// reserved values 'null', 'now()', 'curtime()', 'localtime()', 'localtime',
'utc_date()', 'utc_time()', 'utc_timestamp()'
$data['date'] = 'now()';
// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = 'rade@it-radionica.com';
$data['date'] = 'now()';
// More options
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';
* @param boolean $ingore - INSERT IGNORE (row won't actually be inserted if it
results in a duplicate key)
* @param string $duplicateupdate - ON DUPLICATE KEY UPDATE (The ON DUPLICATE KEY
UPDATE clause can contain multiple column assignments, separated by commas.)
* @return insert id or false
*/
// $db->arrayToInsert($table, $data, $ignore = FALSE, $duplicateupdate = NULL)
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 10
// Next AutoIncrement
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 11
// Array to update
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
// Reserved values: null, now(), curtime(), localtime(), localtime, utc_date(),
utc_time(), utc_timestamp()
$data['email'] = 'null';
$data['date'] = 'now()';
// Array data
// [fealdname] = feald value
$data = array();
$data['id'] = 1; // key
$data['firstname'] = 'foo';
$data['surname'] = 'bar';
$data['email'] = 'rade@it-radionica.com';
$data['date'] = 'now()';
// More options
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';
// Example 12
// Delete row
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// Example 13
// Get table columns
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
echo "<hr /><strong>Example 13 (get table columns)</strong><br />Table columns
are:<br />";
print_r($db->getColumns('table'));
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 14
// Basic Table Operation
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Rename table
$db->renameTable(array('table_copy' => 'table_copy3'));
// Swap table names
$db->renameTable(array('table_copy3' => 'tmp_table', 'table_copy2' =>
'table_copy3', 'tmp_table' => 'table_copy3'));
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 15
// Get database size
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
/** Data Base size in B / KB / MB / GB / TB
* @param string $sizeIn - Size in B / KB / MB / GB / TB
* @param integer $round - Round on decimals
* @param resource $link - Link identifier
* @return - Size in B / KB / MB / GB / TB
*/
// function getDataBaseSize($sizeIn = 'MB', $round = 2, $link = 0)
echo '<hr /><pre>Database size is: ', $db->getDataBaseSize('mb', 2), ' MB</pre>';
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 16
// Loging queries and errors
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 17
// Export Table to CSV
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Export all data
$db->exportTable2CSV('table', 'test_files/test-1.txt');
// Export two or more columns
$db->exportTable2CSV('table', 'test_files/test-2.txt', 'firstname, surname');
// Export two or more columns using array
$db->exportTable2CSV('table', 'test_files/test-3.txt', array('firstname',
'surname', 'date'));
// Export all columns where id < 8 and limit 1, 5
$db->exportTable2CSV('table', 'test_files/test-4.txt', '*', 'id < 8', '1,5');
// More options
/** Export table data to CSV file.
* @param string $table - Table name
* @param string $file - CSV File path
* @param mixed $columns - SQL ( * or column names or array with column names)
* @param string $where - MySQL WHERE Clause
* @param integer $limit - Limit offset
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param string $newLine - New line detelimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return number of inserted rows or false
*/
// $db->exportTable2CSV($table, $file, $columns = '*', $where = NULL, $limit = 0,
$delimiter = ',', $enclosure = '"', $escape = '\\', $newLine = '\n', $showColumns =
TRUE);
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 18
// Query to CSV
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
/** Export query to CSV file.
* @param string $sql - MySQL Query
* @param string $file - CSV File path
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param string $newLine - New line delimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return - File path
*/
// function query2CSV($sql, $file, $delimiter = ',', $enclosure = '"', $escape = '\
\', $newLine = '\n', $showColumns = TRUE)
$path = $db->query2CSV('select * from `table` limit 10', 'test_files/test-
query2csv.csv');
echo '<hr /><pre>Query exported to CSV file: ', $path, '</pre>';
// example 2
$path = $db->query2CSV('select * from `table` limit 2,2', 'test_files/test-
query2csv.csv');
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 19
// Import CSV to Table
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Import all data
$db->importCSV2Table('test_files/test-1.txt', 'table');
// More options
/** Imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Defaul: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or
increment (SQL format only @FIELD is variable with content of that field in CSV
row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")',
'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or table) - this is
important if there is update while inserting (Default: file)
* @param string $newLine - New line detelimiter (Default: \n)
* @return number of inserted rows or false
*/
// Example 20
// Create table from CSV file
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
$db->dropTable('csv_to_table_test');
$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');
$db->dropTable('csv_to_table_test_no_column_names');
$db->createTableFromCSV('test_files/countrylist1.csv',
'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate',
'\r\n');
/** Create table from CSV file and imports CSV data to Table with possibility to
update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or
increment (SQL format only @FIELD is variable with content of that field in CSV
row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")',
'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or generate) - this
is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: \n)
* @return number of inserted rows or false
*/
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"',
$escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine
= '\r\n')
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 21
// Import CSV to Table
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Example 22
// Transactions
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
$queries = array();
$queries[] = 'SELECT ...';
$queries[] = 'INSERT ...';
$queries[] = 'DELETE ...';
$queries[] = '...';
//$db->transaction($queries);
// Get more info on: http://dev.mysql.com/doc/refman/5.0/en/commit.html
/** Transaction
* @param array $qarr - Array with Queries
* @link http://dev.mysql.com/doc/refman/5.0/en/commit.html
*/
// function transaction($qarr = array())
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 23
// String Search and Replace in all or defined Table Columns
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
// Simple
$db->strReplace('table', 'firstname', 'search', 'replace');
// Search array & Replace string
$db->strReplace('table', 'firstname', array('search1', 'search2'), 'replace');
// Search array & Replace array
$db->strReplace('table', 'firstname', array('search1', 'search2'),
array('replace1', 'replace2'));
// Search array of columns (Search array & Replace array) return count of updated
fielsd
$count = $db->strReplace('table', array('firstname', 'surname'), array('search1',
'search2'), array('replace1', 'replace2'));
// String multiple columns
$db->strReplace('table', 'firstname, surname', 'search', 'replace');
// You can set all columns in table as well
$db->strReplace('table', '*', 'search', 'replace');
// More options
/** Replace all occurrences of the search string with the replacement string in
MySQL Table Column(s).
* @param string $table - Table name
* @param mixed $columns - Search & Replace affected Table columns. An array may be
used to designate multiple replacements.
* @param mixed $search - The value being searched for, otherwise known as the
needle. An array may be used to designate multiple needles.
* @param mixed $replace - The replacement value that replaces found search values.
An array may be used to designate multiple replacements.
* @param string $where - WHERE Clause
* @param integer $limit - Limit offset
* @return integer - Affected rows
*/
// function strReplace($table, $columns, $search, $replace, $where = NULL, $limit =
0)
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////
// Example 24
// E-mail on error / die on error
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
// Connect
$db->connect();
$db->emailErrors = TRUE;
$db->dieOnError = TRUE;
$db->emailErrorsTo = array('rade@it-radionica.com');
$db->close();