0% found this document useful (0 votes)
164 views

PHP MySQL Wrapper Class

PHP MySQL Wrapper Class

Uploaded by

Bejace Nyachhyon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views

PHP MySQL Wrapper Class

PHP MySQL Wrapper Class

Uploaded by

Bejace Nyachhyon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

®

PHP MySQL Wrapper Class

USER MANUAL

Copyright © 2021, Bijesh Lal Nyachhyon


Bijesh Lal Nyachhyon
Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Table of Contents 3

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

3. Chapter 2 - Execute arbitrary queries 11


3.1 Select example with fetch result ..................................................................................... 12
3.2 Prepared statements ........................................................................................................ 13
3.3 Prepared statements - mysqlnd driver not installed ..................................................... 14
3.4 Fetch query to array ......................................................................................................... 14
3.5 Multi results ....................................................................................................................... 15
3.6 Rows, Cols num .................................................................................................................. 16
3.7 Count rows ......................................................................................................................... 16

4. Chapter 3 - Execute UPDATE or INSERT queries 19


4.1 Array to insert ................................................................................................................... 20
4.2 Multiple array to insert .................................................................................................... 21
4.3 Array to update ................................................................................................................. 21
4.4 Multiple array to update .................................................................................................. 22

5. Chapter 4 - Delete table rows that match a given condition 25


6. Chapter 5 - Operations with CSV files 27
6.1 Export table to CSV ........................................................................................................... 28
6.2 Export query to CSV .......................................................................................................... 29
6.3 Export table / export query to CSV using fputcsv .......................................................... 29
6.4 Download CSV file from query ......................................................................................... 30
6.5 Import CSV to Table .......................................................................................................... 30
6.6 Import and update CSV to Table ..................................................................................... 31
6.7 Create table from CSV file ................................................................................................. 32

7. Chapter 6 - Operations with XML files 33


7.1 Export query to XML ......................................................................................................... 34

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Table of Contents 4

7.2 Download XML file from query ........................................................................................ 34

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

11. Chapter 10 - Logging / debug 47


11.1 Logging errors .................................................................................................................... 48
11.2 Logging queries ................................................................................................................. 48
11.3 E-mail on error / die on error .......................................................................................... 49
11.4 Errors backtrace and debug ............................................................................................. 49
11.5 Display error example ....................................................................................................... 50

12. Chapter 11 - Draw result / describe table / explain query 51


13. Chapter 12 - Source Code 55
13.1 Main Code (PHP_MySQL_Wrapper.Class.php) ............................................................... 56
13.2 Examples ............................................................................................................................ 85

Index 0

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Introduction
Introduction 6

1 Introduction

This class implements a generic MySQL database access wrapper.

It can:

· Connect to a given MySQL server


· Set the connection character set encoding
· Execute arbitrary queries and return the results in arrays
· Retrieve the columns of a table
· Execute UPDATE or INSERT queries from parameters that define the tables, fields, field values
and conditions
· Execute multiple INSERT or UPDATE queries at once
· Count the number of rows of a table that match a given condition
· Get the next value of an auto-incremented table field
· Delete table rows that match a given condition
· Export, import, update table using CSV files
· Create table from CSV file
· Export query to CSV file
· Replace values in a given table for defined columns
· Rename, copy, truncate or drop table
· Get database size
· Log queries and errors with backtrace information

Copyright © 2021, Bijesh Lal Nyachhyon

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 1 - Connect to a MySQL server
Chapter 1 - Connect to a MySQL server 8

2 Chapter 1 - Connect to a MySQL server


Connect to a given MySQL server

· Connectivity settings
· Connect to a given MySQL server
· Connection examples
· Connection example multi host, db manipulation
· Set the connection character set encoding

2.1 Connectivity settings

Connectivity settings

// Set your connectivity settings


define('MySQL_HOST', 'localhost'); // localhost:3306
define('MySQL_USER', 'root');
define('MySQL_PASS', '');
define('MySQL_DB', 'test');

2.2 Connect to a given MySQL server

Connect to a given MySQL server


$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

//
// ... do queries
//

// Close connection
$db->close();

2.3 Connection examples

Connection examples
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect 1
$db->connect();

//
// Connection 1 queries ...
//

// Close connection 1

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 1 - Connect to a MySQL server 9

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

2.4 Connection example multi host, db manipulation

Connection example multi host, db manipulation


// Inst. 1
$db1 = MySQL_wrapper::getInstance('host1', MySQL_USER, MySQL_PASS, MySQL_DB);

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

// Close connection host 1


$db1->close();

// Close connection host 2


$db2->close();

2.5 Set the connection character set encoding

Set the connection character set encoding

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 1 - Connect to a MySQL server 10

Example 1

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Set charset
$db->charset = 'utf8';;

// Close connection
$db->close();

Example 2

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Set charset
$db->setCharset('utf8');

// Close connection
$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries
Chapter 2 - Execute arbitrary queries 12

3 Chapter 2 - Execute arbitrary queries

Execute arbitrary queries and return the results in arrays

· Select example with fetch result


· Prepared statements
· Prepared statements - mysqlnd driver not installed
· Fetch query to array
· Multi results
· Rows, Cols num
· Count rows

3.1 Select example with fetch result

Select example with fetch result

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// MySQL query
$db->query('SELECT * FROM `table`');

// Int affected rows


if ($db->affected > 0) {
while ($row = $db->fetchArray()) {
// Result
print_r($row);
}
}

// Free result memory


$db->freeResult();

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries 13

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

// Int affected rows


if ($db->affected > 0) {
while ($row = $db->fetchArray()) {
// Print result row
print_r($row);
}
}

// Free result memory


$db->freeResult();

// Close connection
$db->close();

3.2 Prepared statements

Prepared statements (works only with MySQLi!)

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Works only with MySQLi!


$db->extension = 'mysqli';

// Connect
$db->connect();

$name = 'Radovan';

$stmt = $db->call('prepare', 'SELECT * FROM `table` WHERE `firstname` = ?;');


$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something
// print_r($row);
// ...
}

// Close connection

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries 14

$db->close();

3.3 Prepared statements - mysqlnd driver not installed

Prepared statements (works only with MySQLi!) - if mysqlnd driver is not


installed

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

$stmt = $db->call('prepare', 'SELECT `id`, `firstname`, `surname`, `email` FROM


`table` WHERE `level` = ?;');
$stmt->bind_param('i', $level);
$stmt->execute();

$stmt->bind_result($id, $firstname, $surname, $email);


$data = array();
while ($stmt->fetch()) {
$data[] = array(
'id' => $id,
'firstname' => $firstname,
'surname' => $surname,
'email' => $email
);
}

// Print data
print_r($data);

// Close connection
$db->close();

3.4 Fetch query to array

Fetch query to array

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Fetch query to array


$array = $db->fetchQueryToArray('SELECT * FROM `table`');

// Print array
print_r($array);

// Returns only first row


$array = $db->fetchQueryToArray('SELECT * FROM `table`', TRUE);

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries 15

// Print array
print_r($array);

// Close connection
$db->close();

3.5 Multi results

Multi results

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries 16

3.6 Rows, Cols num

Rows, Cols num

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Do query
$db->query('SELECT * FROM `table`');

$cols = $db->numFields();
$rows = $db->numRows();

// ...
echo "Cols: {$cols}, Rows: {$rows}";

// Free result memory


$db->freeResult();

// Close connection
$db->close();

3.7 Count rows

Count rows

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Count all
$count = $db->countRows('table');

// Count with condition


$count2 = $db->countRows('table', "`date` = '" . date("Y-m-d") . "'");

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 2 - Execute arbitrary queries 17

// Close connection
$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Chapter 3 - Execute UPDATE or INSERT
queries
Chapter 3 - Execute UPDATE or INSERT queries 20

4 Chapter 3 - Execute UPDATE or INSERT queries

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

4.1 Array to insert

Array to insert

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = '[email protected]';
// reserved values 'null', 'now()', 'curtime()', 'localtime()', 'localtime',
'utc_date()', 'utc_time()', 'utc_timestamp()'
$data['date'] = 'now()';

// $db->arrayToInsert( ... ) returns insert id


$insert_id = $db->arrayToInsert('table', $data);
echo "Last insert id is: {$insert_id}";

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 3 - Execute UPDATE or INSERT queries 21

4.2 Multiple array to insert

Multiple array to insert

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Array data
// [fealdname] = feald value
$data = array();

// Data set 1
$data[] = array(
'firstname' => 'foo',
'surname' => 'bar',
'email' => '[email protected]',
'date' => 'now()'
);

// Data set 2
$data[] = array(
'firstname' => 'baz',
'surname' => 'qux',
'email' => '[email protected]',
'date' => 'now()'
);

// Data set ...

// $db->arrayToInsert( ... ) multirow returns TRUE on success


$db->arrayToInsert('table', $data);

// Close connection
$db->close();

4.3 Array to update

Array to update

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Array data

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 3 - Execute UPDATE or INSERT queries 22

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

$db->arrayToUpdate('table', $data, "`id` = {$insert_id}");


if ($db->affected > 0) {
echo "Updated: {$db->affected} row(s).";
}

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

4.4 Multiple array to update

Array to update multi-row

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// 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'

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 3 - Execute UPDATE or INSERT queries 23

// ...
);

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

// Data set ...

// $db->arrayToUpdate( ... ) multirow returns TRUE on success


$db->arrayToUpdate('table', $data);

// Close connection
$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Chapter 4 - Delete table rows that match a
given condition
Chapter 4 - Delete table rows that match a given condition 26

5 Chapter 4 - Delete table rows that match a given condition

Delete row(s)

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 5 - Operations with CSV files
Chapter 5 - Operations with CSV files 28

6 Chapter 5 - Operations with CSV files

Operations with CSV files

· Export table to CSV


· Export query to CSV
· Export table / export query to CSV using fputcsv
· Download CSV file from query
· Import CSV to Table
· Import and update CSV to Table
· Create table from CSV file

6.1 Export table to CSV

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
*

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 5 - Operations with CSV files 29

* function exportTable2CSV($table, $file, $columns = '*', $where = NULL, $limit =


0, $delimiter = ',', $enclosure = '"', $escape = '\\', $newLine = '\n',
$showColumns = TRUE);
*/

// Close connection
$db->close();

6.2 Export query to CSV

Export query to CSV

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

$path = $db->query2CSV('select * from `table` limit 10', 'test_files/test-


query2csv.csv');
echo 'Query exported to CSV file: ', $path;

// Example 2
$path = $db->query2CSV('select * from `table` limit 2,2', 'test_files/test-
query2csv.csv');

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

// Close connection
$db->close();

6.3 Export table / export query to CSV using fputcsv

Export table / export query to CSV using fputcsv

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 5 - Operations with CSV files 30

// Connect
$db->connect();

// Don't use mysql outfile


$db->mysqlOutFile = FALSE;

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

6.4 Download CSV file from query

Download CSV file from query

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Set as attachment and execute


$db->attachment()->query2CSV('select * from `table`', 'test.csv');

// Close connection
$db->close();

6.5 Import CSV to Table

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 5 - Operations with CSV files 31

* @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
*
* function importCSV2Table($file, $table, $delimiter = ',', $enclosure = '"',
$escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine
= '\n');
*/

// Close connection
$db->close();

6.6 Import and update CSV to Table

Import and update CSV to Table

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Import and update all data


$db->importUpdateCSV2Table('test_files/countrylist.csv', 'csv_to_table_test');

// Import and update all data


$db->importUpdateCSV2Table('test_files/countrylist.csv', 'csv_to_table_test', ',',
'"', '\\', 1, array(), 'file', '\r\n');
// More options
/** 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: ',')
* @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)

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 5 - Operations with CSV files 32

* @param string $newLine - New line detelimiter (Default: \n)


* @return number of inserted rows or false
*
* function importUpdateCSV2Table($file, $table, $delimiter = ',', $enclosure =
'"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file',
$newLine = '\n');
*/

// Close connection
$db->close();

6.7 Create table from CSV file

Create table from CSV file

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 6 - Operations with XML files
Chapter 6 - Operations with XML files 34

7 Chapter 6 - Operations with XML files

Operations with XML files

· Export query to XML


· Download XML file from query

7.1 Export query to XML

Export query to XML

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Save result as file


$db->query2XML('select * from `table` limit 10', 'items', 'item',
'test_files/test-query2xml.csv');

// Return result as XML


$xml = $db->query2XML('select * from `table` limit 10', 'items', 'item');

/** Export query to XML file or return as XML string


* @param string $query - mysql query
* @param string $rootElementName - root element name
* @param string $childElementName - child element name
* @return string - XML
*
* function query2XML($query, $rootElementName, $childElementName, $file = NULL);
*/

// Close connection
$db->close();

7.2 Download XML file from query

Download XML file from query

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Set as attachment and execute


$db->attachment()->query2XML('select * from `table`', 'root', 'item', 'test.xml');

// Close connection

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 6 - Operations with XML files 35

$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Chapter 7 - Transactions
Chapter 7 - Transactions 38

8 Chapter 7 - Transactions

Transactions

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Queries
$queries = array();
$queries[] = 'SELECT ...';
$queries[] = 'INSERT ...';
$queries[] = 'DELETE ...';
$queries[] = '...';

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 8 - String Search and Replace
Chapter 8 - String Search and Replace 40

9 Chapter 8 - String Search and Replace

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'),
// String multiple columns
$db->strReplace('table', 'firstname, surname', 'search', 'replace');
// You can set all columns in table as well
$db->strReplace('table', '*', 'search', 'replace');
// Whole database
$db->strReplace('*', '*', 'search', 'replace');
// More options
/** Replace all occurrences of the search string with the replacement string in MySQL Table Co
* @param string $table - Table name
* @param mixed $columns - Search & Replace affected Table columns. An array may be us
* @param mixed $search - The value being searched for, otherwise known as the needle
* @param mixed $replace - The replacement value that replaces found search values. An
* @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();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 9 - Basic table operations
Chapter 9 - Basic table operations 42

10 Chapter 9 - Basic table operations

Basic table operations

· Basic Table operations


· Get table columns
· Get database size
· Next AutoIncrement
· Table revision

10.1 Basic Table operations

Basic Table Operation

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// Copy table (with data included)


$db->copyTable('table', 'table_copy');

// Copy table (with data included)


$db->copyTable('table', 'table_copy4');

// Copy table structure


$db->copyTable('table', 'table_copy2', FALSE);

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

// Truncate table (empty)


$db->truncateTable('table_copy2');

// Drop one table


$db->dropTable('table_copy4');

// Drop multiple tables


$db->dropTable(array('table_copy3', 'table_copy2'));

// Close connection
$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 9 - Basic table operations 43

10.2 Get table columns

Get table columns

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Get table columns into array


$array = $db->getColumns('table');

print_r($array);

// Close connection
$db->close();

10.3 Get database size

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 'Database size is: ', $db->getDataBaseSize('mb', 2), ' MB';

// Close connection
$db->close();

10.4 Next AutoIncrement

Get the next value of an auto-incremented table field

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 9 - Basic table operations 44

// Connect to host
$db->connect();

// Returns next auto increment value


$auto_increment = $db->nextAutoIncrement('table');

echo "Next auto increment id is: {$auto_increment}";

// Close connection
$db->close();

10.5 Table revision

Table revision

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Init table revision (do this only once!)


$db->initTableRevision('rev-table');

// Time to restore to ...


$time = '2014-06-25 14:26:03';

/** Create table from current revision time


* @param string $table - New table name
* @param string $rev_table - Revision table (origin table)
* @param string $id_field - Unique field name
* @param datetime - Revision time
*
* function createTableFromRevisionTime($table, $rev_table, $id_field, $time);
*/

$db->createTableFromRevisionTime('rev-table' . '-' . $time, 'rev-table', 'id',


$time);

/** Restore table from current revision time


* @param string $table - New table name
* @param string $id_field - Unique field name
* @param datetime - Revision time
*
* function restoreTableFromRevisionTime($table, $id_field, $time);
*/

$db->restoreTableFromRevisionTime('rev-table', 'id', $time);

// Close connection
$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 9 - Basic table operations 45

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Chapter 10 - Logging / debug
Chapter 10 - Logging / debug 48

11 Chapter 10 - Logging / debug

Logging / debug

· Logging errors
· Logging queries
· E-mail on error / die on error
· Errors backtrace and debug
· Display error example

11.1 Logging errors

Logging errors

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

// This is useful to be TRUE!


$db->logErrors = TRUE;

// Default is FALSE, use TRUE only for debuging (security reasons!)


$db->displayError = TRUE;

// Date / Time format for log


$db->dateFormat = "Y-m-d H:i:s";

// Log file
$db->logFilePath = 'log-mysql.txt';

// This query has error


$db->query('SELECT * FROM `table` asfd!@#$');

// Close connection
$db->close();

11.2 Logging queries

Logging queries

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect to host
$db->connect();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 10 - Logging / debug 49

// Default is FALSE, use TRUE only for debuging


$db->logQueries = TRUE;

// Log file
$db->logFilePath = 'log-mysql.txt';

// Query for this function will be logged


$db->getColumns('table');

// Query will be logged as well ...


$db->query('SELECT * FROM `table`;');

// Close connection
$db->close();

11.3 E-mail on error / die on error

E-mail on error / die on error

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Send mail on error


$db->emailErrors = TRUE;

// Die on errors
$db->dieOnError = TRUE;

// Array of emails
$db->emailErrorsTo = array('[email protected]');

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

11.4 Errors backtrace and debug

Errors backtrace and debug

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 10 - Logging / debug 50

// Connect to host
$db->connect();

// Default is FALSE, use TRUE only for debuging (security reasons!)


$db->displayError = TRUE;

// This query has error


$db->query('SELECT * FROM `table` asfd!@#$');

// Close connection
$db->close();

11.5 Display error example

Display error example

Query fail: SELECT * FROM `table` asfd!@#$


- Error No: 1064
- Error: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '!@#$' at line 1
- Call: Function query in C:\xampp\htdocs\Git\PHP_MySQL_wrapper\test.php on line
29

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 11 - Draw result / describe table /
explain query
Chapter 11 - Draw result / describe table / explain query 52

12 Chapter 11 - Draw result / describe table / explain query

Draw result / describe table / explain query

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Draw query result data in table


$array = $db->fetchQueryToArray('SELECT * FROM `table` LIMIT 2;');
$db->drawTable($array, 'Test table contents');

/** Draw ascii table


* @param array $data - Multidimensional array of data
* @param string $title - Table header
* @return void
*
* function drawTable($data, $title = NULL);
*/

// Draw query execution plan in table


$db->explain('SELECT * FROM `table`;');

// Draw information about the columns in a table


$db->describe('table');

// Close connection
$db->close();

Draw table output:


+---------------------------------------------------------------+
| Test table contents |
+----+-----------+---------+-----------------------+------------+
| id | firstname | surname | email | date |
+----+-----------+---------+-----------------------+------------+
| 1 | foo | bar | [email protected] | 2014-10-02 |
| 2 | Radovan | Janjic | [email protected] | 2014-10-02 |
+----+-----------+---------+-----------------------+------------+

Explain output:
+-------------------------------------------------------------------------------------
-+
| Explain MySQL Query
|
+----+-------------+-------+------+---------------+-----+---------+-----+------
+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
|
+----+-------------+-------+------+---------------+-----+---------+-----+------
+-------+

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 11 - Draw result / describe table / explain query 53

| 1 | SIMPLE | table | ALL | | | | | 98 |


|
+----+-------------+-------+------+---------------+-----+---------+-----+------
+-------+

Describe output:
+------------------------------------------------------------------+
| test |
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | | auto_increment |
| firstname | varchar(100) | NO | | | |
| surname | varchar(100) | NO | | | |
+-----------+--------------+------+-----+---------+----------------+

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Thi s pa ge i s i ntenti ona l l y l eft bl a nk.
Remove thi s text from the ma nua l
templ a te i f you wa nt i t compl etel y bl a nk.
Chapter 12 - Source Code
Chapter 12 - Source Code 56

13 Chapter 12 - Source Code

· Main Code (PHP_MySQL_Wrapper.Class.php)


· Example

13.1 Main Code (PHP_MySQL_Wrapper.Class.php)


<?php
/******************************************************************
*
* File name: PHP_MySQL_Wrapper.Class.php
* Projectname: PHP MySQL Wrapper Class
* Version: 1.6.1
* Author: Bijesh Lal Nyachhyon <[email protected]>
* Last modified: 31 03 2021
* Copyright (C): 2021 Bijesh Lal Nyachhyon, All Rights Reserved
*
******************************************************************/

/** Execute MySQL queries defined programmatically.


* @param string $server - MySQL Host name or ( host:port )
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
*/
class MySQL_wrapper {

/** Class Version


* @var float
*/
private $version = '1.6.2';

/** Store the single instance


* @var array
*/
private static $instance = array();

/** MySQL Host name


* @var string
*/
private $server = NULL;

/** MySQL User


* @var string
*/
private $username = NULL;

/** MySQL Password


* @var string
*/
private $password = NULL;

/** MySQL Database


* @var string
*/

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 57

private $database = NULL;

/** mysql / mysqli


* @var string
*/
public $extension = 'mysqli';

/** Connection Charset (Default: UTF-8)


* @var string
*/
public $charset = 'utf8';

/** Error Description


* @var string
* */
public $error = NULL;

/** Error Number


* @var integer
*/
public $errorNo = 0;

/** Display Errors (Default: TRUE)


* @var boolean
*/
public $displayError = TRUE;

/** Link
* @var resource
*/
public $link = 0;

/** Query
* @var resource
*/
public $query = 0;

/** Affected Rows


* @var integer
*/
public $affected = 0;

/** Previous query


* @var string
*/
public $prevQuery = NULL;

/** Log Queries to file (Default: FALSE)


* @var boolean
*/
public $logQueries = FALSE;

/** Log Errors to file (Default: FALSE)


* @var boolean
*/
public $logErrors = FALSE;

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 58

/** Stop script execution on error (Default: FALSE)


* @var boolean
*/
public $dieOnError = FALSE;

/** E-mail errors (Default: FALSE)


* @var boolean
*/
public $emailErrors = FALSE;

/** E-mail errors to (array with emails)


* @var array
*/
public $emailErrorsTo = array();

/** E-mail errors subject


* @var string
*/
public $emailErrorsSubject = 'MySQL ERROR ON SERVER: %s';

/** Log Date Format (Default: Y-m-d H:i:s)


* @var string
*/
public $dateFormat = 'Y-m-d H:i:s';

/** Log File Path (Default: log-mysql.txt)


* @var string
*/
public $logFilePath = 'log-mysql.txt';

/** Reserved words for array to ( insert / update )


* @var array
*/
public $reserved = array('null', 'now()', 'current_timestamp', 'curtime()',
'localtime()', 'localtime', 'utc_date()', 'utc_time()', 'utc_timestamp()');

/** Start of MySQL statement for array to ( insert / update )


* @var string
*/
public $statementStart = 'sql::';

/** REGEX
* @var array
*/
private $REGEX = array('LIMIT' => '/limit[\s]+([\d]+[\s]*,[\s]*[\d]+[\s]*|[\d]
+[\s]*)$/i', 'COLUMN' => '/^[a-z0-9_\-\s]+$/i');

/** Use MySQL SELECT ... INTO OUTFILE (Default: TRUE)


* @var boolean
*/
private $attachment = FALSE;

/** Use MySQL SELECT ... INTO OUTFILE (Default: TRUE)


* @var boolean
*/
public $mysqlOutFile = TRUE;

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 59

/** Singleton declaration


* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
* @return - singleton instance
*/
public static function getInstance($server = NULL, $username = NULL, $password
= NULL, $database = NULL) {
$md5 = md5(implode('|', array($server, $username, $password, $database)));
if (empty(self::$instance[$md5])) {
self::$instance[$md5] = new MySQL_wrapper($server, $username,
$password, $database);
}
return self::$instance[$md5];
}

/** Protected constructor to prevent creating a new instance of the


MySQL_wrapper via the `new` operator from outside of this class.
* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
*/
protected function __construct($server = NULL, $username = NULL, $password =
NULL, $database = NULL) {
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}

/** Private clone method to prevent cloning of the MySQL_wrapper instance.


* @return void
*/
private function __clone() {
// ... void
}

/** Private unserialize method to prevent unserializing of the MySQL_wrapper


instance.
* @return void
*/
private function __wakeup() {
// ... void
}

/** Call function


* @param string $func - function name
* @param string $params - MySQL User
* @param return
*/
public function call($func) {
// Functions without link parameter
$l = array('free_result', 'fetch_assoc', 'num_rows', 'num_fields',
'fetch_object', 'fetch_field_direct');
// Add return value

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 60

$r = array('free_result' => TRUE);


// Params
if (func_num_args() >= 2) {
$params = func_get_args();
unset($params[0]);
if ($this->extension == 'mysql') {
$params = in_array($func, $l) ? $params : array_merge($params,
array($this->link));
} elseif ($this->extension == 'mysqli') {
$params = in_array($func, $l) ? $params : array_merge(array($this-
>link), $params);
}
} else {
$params = array($this->link);
}
// Return
if (in_array($func, array_keys($r)) && $this->extension == 'mysqli') {
call_user_func_array("{$this->extension}_{$func}", $params);
return $r[$func];
} else {
return call_user_func_array("{$this->extension}_{$func}", $params);
}
}

/** 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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 61

if (mysqli_connect_errno($this->link)) {
$this->error("Failed to connect to MySQL: " .
mysqli_connect_error());
return FALSE;
} else {
$this->setCharset();
return TRUE;
}
}
}

/** Sets the default charset for the current connection.


* @param string $charset - A valid charset name ( If not defined $this-
>charset whill be used)
* @return boolean
*/
public function setCharset($charset = NULL) {
$this->charset = $charset ? $charset : $this->charset;
$this->call('set_charset', $this->charset) or $this->error("Error loading
character set {$this->charset}");
}

/** Checks whether or not the connection to the server is working.


* @param void
* @return boolean
*/
public function ping() {
return $this->call('ping');
}

/** Reconnect to the server.


* @param void
* @return boolean
*/
public function reconnect() {
$this->close();
return $this->connect();
}

/** 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) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 62

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;
}

/** Get number of fields in result


* @param resource $query - MySQL Query Result
* @return integer - Retrieves the number of fields from a query
*/
public function numFields($query = 0) {
return intval($this->call('num_fields', $query ? $query : $this->query));
}

/** Get number of rows in result


* @param resource $query - MySQL Query Result
* @return integer - Retrieves the number of rows from a result set
*/
public function numRows($query = 0) {
return intval($this->call('num_rows', $query ? $query : $this->query));
}

/** Get number of rows in result


* @param resource $query - Result resource that is being evaluated ( Query
Result )
* @return bool
*/
public function freeResult($query = 0) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 63

$this->call('free_result', $query ? $query : $this->query) or $this-


>error("Result could not be freed.");
}

/** Get Columns names into array


* @param string $table - Table name
* @return array $columns - Names of Fields
*/
public function getColumns($table) {
$q = $this->query("SHOW COLUMNS FROM `{$table}`;");
$columns = array();
while ($row = $this->fetchArray($q)) $columns[] = $row['Field'];
$this->freeResult($q);
return $columns;
}

/** 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;
}
}

/** Returns array with fetched associative rows.


* @param string $sql - MySQL Query
* @param string $fetchFirst - Fetch only first row
* @return array
*/
public function fetchQueryToArray($sql, $fetchFirst = FALSE) {
if ($fetchFirst) {
$sql = rtrim(trim($sql), ';');
$sql = preg_replace($this->REGEX['LIMIT'], 'LIMIT 1;', $sql);
if (substr($sql, -strlen('LIMIT 1;')) !== 'LIMIT 1;') {
$sql .= ' LIMIT 1;';
}
}
$q = $this->query($sql);
$array = array();
if ($fetchFirst && $this->affected > 0) {
$array = $this->fetchArray($q);
} else {
while ($row = $this->fetchArray($q)) {
$array[] = $row;
}
}
$this->freeResult($q);
return $array;
}

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 64

/** Escapes special characters in a string for use in an SQL statement.


* @param string $string - unescaped string
* @return string
*/
public function escape($string) {
if (!version_compare(PHP_VERSION, '5.4.0') >= 0) {
$string = get_magic_quotes_gpc() ? stripslashes($string) : $string;
}
return $this->call('real_escape_string', $string);
}

/** 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
* @return number of updated rows or false
*/
public function arrayToUpdate($table, $data, $where = NULL, $limit = 0) {
if (is_array(reset($data))) {
$cols = array();
foreach (array_keys($data[0]) as $c) {
$cols[] = "`{$c}` = VALUES(`{$c}`)";
}
return $this->arrayToInsert($table, $data, TRUE, implode(', ', $cols));
}
$fields = array();
foreach ($data as $key => $val) {
if (in_array(strtolower($val), $this->reserved)) {
$fields[] = "`{$key}` = " . strtoupper($val);
} elseif (preg_match('/^' . preg_quote($this->statementStart) . '/i',
$val)) {
$fields[] = "`{$key}` = " . preg_replace('/^' . preg_quote($this-
>statementStart) . '/i', NULL, $val);
} else {
$fields[] = "`{$key}` = '{$this->escape($val)}'";
}
}
return (!empty($fields)) ? $this->query("UPDATE `{$table}` SET " .
implode(', ', $fields) . ($where ? " WHERE {$where}" : NULL) . ($limit ? " LIMIT
{$limit}" : NULL) . ";") ? $this->affected : FALSE : FALSE;
}

/** Creates an sql string from an associate array


* @param string $table - Table name
* @param array $data - Data array Eg. array('column' => 'val') or multirows
array(array('column' => 'val'), array('column' => 'val2'))
* @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
*/
public function arrayToInsert($table, $data, $ignore = FALSE, $duplicateupdate
= NULL) {
$multirow = is_array(reset($data));

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 65

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
*/

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 66

public function importCSV2Table($file, $table, $delimiter = ',', $enclosure =


'"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file',
$newLine = FALSE) {
$file = file_exists($file) ? realpath($file) : NULL;
$file = realpath($file);
if (!file_exists($file)) {
$this->error('ERROR', "Import CSV to Table - File: {$file} doesn't
exist.");
return FALSE;
}

if ($newLine === FALSE) {


$newLine = $this->detectEOL($file);
}

$sql = "LOAD DATA LOCAL INFILE '{$this->escape($file)}' " .


"INTO TABLE `{$table}` " .
"COLUMNS TERMINATED BY '{$delimiter}' " .
"OPTIONALLY ENCLOSED BY '{$enclosure}' " .
"ESCAPED BY '{$this->escape($escape)}' " .
"LINES TERMINATED BY '{$newLine}' " .
($ignore ? "IGNORE {$ignore} LINES" : NULL);

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}.");
}
}

foreach ($columns as &$c) {


$c = (in_array($c, array_keys($update))) ? '@' . $c : "`{$c}`";
}
$sql .= " (" . implode(', ', $columns) . ") ";

$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: ',')

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 67

* @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
*/
public function importUpdateCSV2Table($file, $table, $delimiter = ',',
$enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom =
'file', $newLine = FALSE) {
$tmp_name = "{$table}_tmp_" . rand();

// Create tmp table


$this->query("CREATE TEMPORARY TABLE `{$tmp_name}` LIKE `{$table}`;");

// Remove auto_increment if exists


$change = array();
$this->query("SHOW COLUMNS FROM `{$tmp_name}` WHERE `Key` NOT LIKE '';");
if ($this->affected > 0) {
while ($row = $this->fetchArray()) {
$change[$row['Field']] = "CHANGE `{$row['Field']}` `{$row['Field']}
` {$row['Type']}";
}
$this->freeResult();
}

if ($getColumnsFrom == 'file') {
// Get first line of 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}.");
}

// Drop columns that are not in CSV file


foreach ($this->getColumns($table) as $c) {
if (!in_array($c, $columns, TRUE)) {
$change[$c] = "DROP COLUMN `{$c}`";
}
}
}

if (count($change) > 0) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 68

$this->query("ALTER TABLE `{$tmp_name}` " . implode(', ', $change) .


";");
}

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

foreach ($columns as $c) {


$cols[] = "`{$c}` = VALUES(`{$c}`)";
}

$this->query("INSERT INTO `{$table}` ( `" . implode('`, `', $columns) .


"` ) SELECT * FROM `{$tmp_name}` ON DUPLICATE KEY UPDATE " . implode(', ', $cols) .
";");
$i = $this->affected;

// Drop tmp table


$this->query("DROP TEMPORARY TABLE `{$tmp_name}`;");

return $i;
}

/** 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 delimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return - File path
*/
public function exportTable2CSV($table, $file, $columns = '*', $where = NULL,
$limit = 0, $delimiter = ',', $enclosure = '"', $escape = '\\', $newLine = '\n',
$showColumns = TRUE) {
// Without OUTFILE or as attachment
if ($this->attachment || !$this->mysqlOutFile) {
return $this->query2CSV("SELECT * FROM `$table`" . ($where ? " WHERE
{$where}" : NULL) . ($limit ? " LIMIT {$limit}" : NULL), $file, $delimiter,
$enclosure, $escape, $newLine, $showColumns);
}

$fh = fopen($file, 'w') or $this->error("ERROR", "Can't create CSV file:


{$file}");
if (!$fh) {
return FALSE;
}

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 69

fclose($fh);
$file = realpath($file);
unlink($file);

// Put columns into array if not *


if ($columns != '*' && !is_array($columns)) {
$stringColumns = $columns;
$columns = array();
foreach (explode(',', $stringColumns) as $c) {
$columns[] = trim(str_replace(array("'", "`", "\""), NULL, $c));
}
}

// Prepare SQL for column names


if ($showColumns) {
$tableColumnsArr = array();
if ($columns == '*') {
foreach ($this->getColumns($table) as $c)
$tableColumnsArr[] = "'{$c}' AS `{$c}`";
} elseif (is_array($columns)) {
foreach ($columns as $c)
$tableColumnsArr[] = "'{$c}' AS `{$c}`";
}
$columnsSQL = "SELECT " . implode(', ', $tableColumnsArr);
}

$sql = "SELECT " . (is_array($columns) ? '`' . implode('`, `', $columns) .


'`' : $columns) . " FROM `{$table}`" . ($where ? " WHERE {$where}" : NULL) .
($limit ? " LIMIT {$limit}" : NULL);
$sql = (($showColumns) ? "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;
}

/** Set attachment var and return object.


* @param void
* @return - obj
*/
function attachment() {
$this->attachment = TRUE;
return $this;
}

/** 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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 70

*/
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;
}
}

// Check if location is writable and unlink


$fh = fopen($file, 'w') or $this->error("ERROR", "Can't create CSV file:
{$file}");
if (!$fh) {
return FALSE;
}
fclose($fh);
$file = realpath($file);
unlink($file);

// Remove ; from end of query


$sql = trim(rtrim(trim($sql), ';'));
// Prepare SQL for column names
if ($showColumns) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 71

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

/** Export query to XML file or return as XML string


* @param string $query - mysql query
* @param string $rootElementName - root element name
* @param string $childElementName - child element name
* @return string - XML
*/
public function query2XML($query, $rootElementName, $childElementName, $file =
NULL) {
// Save to file or attachment
if ($this->attachment || !empty($file)) { //echo $file; exit;
$fh = fopen($this->attachment ? 'php://output' : $file, 'w') or $this-
>error("ERROR", "Can't create XML file: {$file}");
if (!$fh) {
return FALSE;
} elseif ($this->attachment) {
// Send response headers
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="' .
basename($file));
header('Pragma: no-cache');
header('Expires: 0');
$this->attachment = FALSE;
} else {
$file = realpath($file);
}
$saveToFile = TRUE;
} else {
$saveToFile = FALSE;
}

// Do query

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 72

$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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 73

* @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: auto detection use \n,
\r\n ...)
* @return number of inserted rows or false
*/
public function createTableFromCSV($file, $table, $delimiter = ',', $enclosure
= '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file',
$newLine = FALSE) {
$file = file_exists($file) ? realpath($file) : NULL;
if ($file === NULL) {
$this->error('ERROR', "Create Table form CSV - File: {$file} doesn't
exist.");
return FALSE;
} else {
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
$data = explode($delimiter, str_replace($enclosure, NULL,
trim($line)));
$columns = array();
$i = 0;

foreach ($data as $c) {


if ($getColumnsFrom == 'generate') {
$c = 'column_' . $i++;
}
if (preg_match($this->REGEX['COLUMN'], $c)) {
$columns[] = "`{$c}` BLOB NULL";
} else {
$this->error('ERROR', "Invalid column name: {$c} in file:
{$file}");
return FALSE;
}
}

$this->query("CREATE TABLE `{$table}` ( " . implode(', ', $columns) . "


) ENGINE=InnoDB DEFAULT CHARSET={$this->charset};");
if ($this->importCSV2Table($file, $table, $delimiter, $enclosure,
$escape, $ignore, $update, ($getColumnsFrom == 'generate') ? 'table' : 'file',
$newLine) > 0) {
$columns = $this->fetchQueryToArray("SELECT * FROM `{$table}`
PROCEDURE ANALYSE ( 10, 30 );", FALSE);
$change = array();
foreach ($columns as $c) {
$c['Field_name'] = implode('`.`', explode('.',
$c['Field_name']));
$change[] = "CHANGE `{$c['Field_name']}` `{$c['Field_name']}`
{$c['Optimal_fieldtype']}";

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 74

}
$this->query("ALTER TABLE `{$table}` " . implode(', ', $change) .
";");
}
}
}

/** Rename table(s)


* @param array $table - Names of the tables eg -> array('old_table' =>
'new_table') or array('table1' => 'tmp_table', 'table2' => 'table1', 'tmp_table' =>
'table1')
* @return resource or false
*/
public function renameTable($table) {
$rename = array();
foreach ($table as $old => $new) {
$rename[] = "`{$old}` TO `{$new}`";
}
return $this->query("RENAME TABLE " . implode(', ', $rename) . ";");
}

/** Copy table structure or structure and data.


* @param string $table - Table name
* @param string $new_table - New table name
* @param boolean $data - Copy table data
* @return resource or false
*/
public function copyTable($table, $new_table, $data = TRUE) {
$r = $this->query("CREATE TABLE `{$new_table}` LIKE `{$table}`;");
return ($r && $data) ? $this->query("INSERT INTO `{$new_table}` SELECT *
FROM `{$table}`;") : $r;
}

/** Truncate table


* @param string $table - Table name
* @return resource or false
*/
public function truncateTable($table) {
return $this->query("TRUNCATE TABLE `{$table}`;");
}

/** Drop table(s)


* @param array $table - Names of the tables eg -> array('table1', 'table2')
* @param boolean $if_exists - Use IF EXISTS to prevent an error from occurring
for tables that do not exist.
* @return resource or false
*/
public function dropTable($table, $if_exists = TRUE) {
return $this->query("DROP TABLE " . ($if_exists ? "IF EXISTS " : NULL) .
"`" . (is_array($table) ? implode('`, `', $table) : $table) . "`;");
}

/** 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
* @return - Size in B / KB / MB / GB / TB
*/

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 75

public function getDataBaseSize($sizeIn = 'MB', $round = 2) {


$r = $this->query("SELECT ROUND( SUM( `data_length` + `index_length` ) " .
str_repeat('/ 1024 ', array_search(strtoupper($sizeIn), array('B', 'KB', 'MB',
'GB', 'TB'))) . ", {$round} ) `size` FROM `information_schema`.`TABLES` WHERE
`table_schema` LIKE '{$this->database}' GROUP BY `table_schema`;");
if ($r !== FALSE) {
$row = $this->fetchArray($r);
$this->freeResult($r);
return $row['size'];
} else {
return FALSE;
}
}

/** Retrieves the ID generated for an AUTO_INCREMENT column by the previous


query.
* @param void
* @return integer
*/
public function insertID() {
return $this->call('insert_id');
}

/** 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;
}
}

/** Retrieves next auto increment value.


* @param string $table - Table name
* @return integer or false
*/
public function nextAutoIncrement($table) {
$r = $this->query("SHOW TABLE STATUS LIKE '{$table}';");
if ($r !== FALSE) {
$row = $this->fetchArray();
$this->freeResult($r);
return $row['Auto_increment'];
} else {
return FALSE;
}
}

/** Delete row(s) from table based on certain conditions.


* @param string $table - Table name

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 76

* @param string $where - WHERE Clause


* @param integer $limit - Limit offset
* @return number of deleted rows or false
*/
public function deleteRow($table, $where = NULL, $limit = 0) {
return $this->query("DELETE FROM `{$table}`" . ($where ? " WHERE {$where}"
: NULL) . ($limit ? " LIMIT {$limit}" : NULL) . ";") ? $this->affected : 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)) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 77

$affected += $this->strReplace($row['table'], $row['columns'],


$search, $replace, $where, $limit);
}
}
$this->freeResult($q);
return $affected;
}

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

/** Begin Transaction


* @param void
*/
public function begin() {
$this->query("START TRANSACTION;");
return $this->query("BEGIN;");
}

/** Commit
* @param void
*/
public function commit() {
return $this->query("COMMIT;");

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 78

/** 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;
}
}

/** Init table revision


* @param string $table - Table name
*/
public function initTableRevision($table) {
// Revision table name
$rev_table = "{$table}_revision";

// Create tmp table


$this->query("CREATE TABLE `{$rev_table}` LIKE `{$table}`;");

// Remove auto_increment if exists


$change = array();
$this->query("SHOW COLUMNS FROM `{$rev_table}` WHERE `Key` NOT LIKE '' OR
`Default` IS NOT NULL;");
if ($this->affected > 0) {
while ($row = $this->fetchArray()) {
$change[$row['Field']] = "CHANGE `{$row['Field']}` `{$row['Field']}
` {$row['Type']} DEFAULT " . (($row['Extra']) ? 0 : 'NULL');
}
$this->freeResult();
}
// Alter revision table
$this->query("ALTER TABLE `{$rev_table}` " . implode(', ', $change) . ";");

// Remove indexes from revision table


$this->query("SHOW INDEXES FROM `{$rev_table}`;");
$drop = array();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 79

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 80

"BEGIN " .
"INSERT INTO `{$rev_table}` (`revision_action`,
`revision_timestamp`, `revision_user`, `" . implode('`, `', $columns) . "`) VALUES
('DELETE', NOW(), USER(), OLD.`" . implode('`, OLD.`', $columns) . "`); " .
"END;"
);

// Insert existing data into revision table


$this->query(
"INSERT INTO `{$rev_table}` (`revision_action`, `revision_timestamp`,
`revision_user`, `" . implode('`, `', $columns) . "`) " .
"SELECT 'INSERT' AS `revision_action`, NOW() AS `revision_timestamp`,
USER() AS `revision_user`, `{$table}`.* FROM `{$table}`;"
);
}

/** Create table from current revision time


* @param string $table - New table name
* @param string $rev_table - Revision table (origin table)
* @param string $id_field - Unique field name
* @param datetime - Revision time
*/
public function createTableFromRevisionTime($table, $rev_table, $id_field,
$time) {
$time = strtotime($time);
$columns = $this->getColumns($rev_table);

// Status at the time, use for update


$this->query(
"CREATE TABLE `{$table}` " .
"SELECT `" . implode('`, `', $columns) . "` " .
"FROM (" .
"SELECT `" . implode('`, `', $columns) . "` " .
"FROM `{$rev_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 `{$rev_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}`;"
);
}

/** Restore table from current revision time


* @param string $table - New table name
* @param string $id_field - Unique field name
* @param datetime - Revision time
*/
public function restoreTableFromRevisionTime($table, $id_field, $time) {
$time = strtotime($time);
$columns = $this->getColumns($table);
$cols = array();
foreach ($columns as $c) {

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 81

$cols[] = "`{$c}` = VALUES(`{$c}`)";


}

// Remove added items after defined time


$this->query(
"DELETE FROM `{$table}` " .
"WHERE `{$id_field}` IN(" .
"SELECT `{$id_field}` " .
"FROM `{$table}_revision` " .
"WHERE `revision_action` = 'INSERT' AND `revision_timestamp` >
STR_TO_DATE('" . date('Y-m-d H:i:s', $time) . "', '%Y-%m-%d %H:%i:%s') " .
"GROUP BY `{$id_field}`" .
");"
);

// 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) . ";"
);
}

/** Prints error message


* @param string $msg - Message
* @param boolean $web - HTML (TRUE) or Plaint text
*/
private function error($msg, $web = FALSE) {
if ($this->displayError || $this->logErrors || $this->emailErrors) {
if ($this->link) {
$this->error = $this->call('error');
$this->errorNo = $this->call('errno');
}
$nl = empty($_SERVER['REMOTE_ADDR']) ? PHP_EOL : "<br>" . PHP_EOL;
$web = empty($_SERVER['REMOTE_ADDR']) ? FALSE : $web;
$error = ($web ? "{$nl} - Error No: <a
href=\"http://search.oracle.com/search/search?q={$this->errorNo}
&amp;group=MySQL\">{$this->errorNo}</a>{$nl} - Error: {$this->error}" : "{$nl} -
Error No: {$this->errorNo}{$nl} - Error: {$this->error}{$nl} - Call: {$this-
>backtrace()}") . PHP_EOL;
if ($this->logErrors)
$this->log('ERROR', "NO -> {$this->errorNo} - DESC -> {$this-
>error} - CALL -> {$this->backtrace()}");
if ($this->displayError)

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 82

echo $msg, $this->link ? $error : NULL;


if ($this->emailErrors) {
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=UTF-8";
$headers[] = "From: MySQL ERROR REPORTING <no-
reply@{$_SERVER['SERVER_ADDR']}>";
$headers[] = "Reply-To: Recipient Name <no-
reply@{$_SERVER['SERVER_ADDR']}>";
$headers[] = "Subject: {$this->emailErrorsSubject}";
$headers[] = "X-Mailer: PHP/" . phpversion();
$m = array();
$m['ENV'] = $_SERVER['SERVER_NAME'];
$m['TIME'] = date($this->dateFormat);
$m['SCRIPT'] = $_SERVER['PHP_SELF'];
$m['CALL'] = $this->backtrace();
$m['ERROR NO'] = $this->errorNo;
$m['ERROR'] = $this->error;
$m['MESSAGE'] = $msg;
$message = array();
foreach ($m as $k => $v) {
$message[] = sprintf("%-10s%s", $k, $v);
}
mail(implode(', ', $this->emailErrorsTo), sprintf($this-
>emailErrorsSubject, $_SERVER['SERVER_NAME']), implode("\r\n", $message),
implode("\r\n", $headers));
}
}
!$this->dieOnError || die();
}

/** Logs queries or / and errors to file


* @param string $type - Log type
* @param string $log - Message
*/
private function log($type, $log) {
try {
$fh = fopen($this->logFilePath, 'a');
fwrite($fh, date($this->dateFormat) . " - {$type} -> {$log}" .
PHP_EOL);
fclose($fh);
} catch(Exception $e) {
$this->error($e->getMessage());
}
}

/** Debug Backtrace


* @param void
* @return string - Backtrace
*/
private function backtrace() {
foreach (debug_backtrace() as $t) {
if ($t['file'] != __FILE__) {
return "Function {$t['function']} in {$t['file']} on line
{$t['line']}";
}
}

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 83

/** Draw table with explain


* @param string $sql - MySQL query
* @return void
*/
public function explain($sql) {
$data = $this->fetchQueryToArray('EXPLAIN ' . $sql);
$this->drawTable($data, 'Explain MySQL Query');
}

/** Draw table with describe


* @param string $table - Table name
* @return void
*/
public function describe($table) {
$data = $this->fetchQueryToArray('DESCRIBE `' . $table . '`;');
$this->drawTable($data, $table);
}

/** Draw ascii table


* @param array $data - Multidimensional array of data
* @param string $title - Table header
* @return void
*/
public function drawTable($data, $title = NULL) {
// No data
if (empty($data)) {
return FALSE;
}
// Use array keys for fild names
$h = array_keys($data[0]);
$header = array();
foreach ($h as $name) {
$header[$name] = $name;
}
// Prepend header
array_unshift($data, $header);
// Find max strlen
$p = array();
$l = array();
foreach ($data as $elm) {
foreach ($elm as $key => $val) {
// Define index
if (!isset($l[$key], $l[$key])) {
$l[$key] = 0;
$p[$key] = 0;
}
// Find max
$l[$key] = strlen($val);
if ($l[$key] > $p[$key]) {
$p[$key] = $l[$key];
}
}
}
// Return data
$ret = array();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 84

// 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>';
}

/** Get Microtime


* @return float - Current time
*/
private function getMicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float) $usec + (float) $sec);
}

/** Detect EOL from file


* @param string - File path
* @retrun - EOL chr
*/
private function detectEOL($file) {
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
foreach (array("\r\n", "\r", "\n") as $eol) {
if (substr_compare($line, $eol, -strlen($eol)) === 0) {
return $eol;

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 85

}
}
return FALSE;
}
}

13.2 Examples

<?php
/*

PHP MySQL Wrapper Exmaples

PHP version required (PHP 5)

*/

require "PHP_MySQL_Wrapper.Class.php";

// set your connectivity settings here


define('MySQL_HOST', 'localhost');
define('MySQL_USER', 'root');
define('MySQL_PASS', '');
define('MySQL_DB', 'test');

/*
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);

// Connect
$db->connect();

// Test table sql for examples


$db->query("CREATE TABLE IF NOT EXISTS `table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(250) NOT NULL,
`surname` varchar(250) NOT NULL,
`email` varchar(500) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;");

// Some dummy data, uncomment to insert


if (!$db->countRows('table') > 0)
$db->query("INSERT INTO `table` (`id`, `firstname`, `surname`, `email`, `date`)
VALUES
(1, 'Radovan', 'Janjic', '', '2012-11-04'),
(2, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),
(3, 'Radovan', 'Janjic''', '[email protected]', '2012-11-04'),
(4, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),
(5, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 86

(6, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),


(7, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),
(8, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),
(9, 'Radovan', 'Janjic', '[email protected]', '2012-11-04'),
(10, 'Radovan', 'Janjic', '[email protected]', '2012-11-04');");

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

// Connect with new link


$db->connect(TRUE);
//

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 87

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

// Host 2 instance (MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB) -> use another


connection info
$db2 = 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
//

// Close connection host 1


$db1->close();

// Close connection host 2


$db2->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

// Int affected rows


if ($db->affected) {
echo "<hr /><strong>Example 4 ( fetch row - array)</strong><pre>";
while ($row = $db->fetchArray()) {
print_r($row);
}
echo "</pre>";
}
$db->freeResult();

// Escape string

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 88

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

// Int affected rows


if ($db->affected) {
echo "<hr /><strong>Example 4 ( fetch row - array)</strong><pre>";
while ($row = $db->fetchArray()) {
print_r($row);
}
echo "</pre>";
}

$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 = $db->call('prepare', 'SELECT * FROM `table` WHERE `firstname` = ?;');


$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something
// print_r($row);
// ...
}

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 89

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

// Returns only first row


print_r($db->fetchQueryToArray('SELECT * FROM `table`', TRUE));
echo "</pre>";
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 90

///////////////////////////////////////////////////////////////////////////////////
////////

// Example 7
// Rows, Cols num
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();

$db->query('SELECT * FROM `table`;');

$cols = $db->numFields();
$rows = $db->numRows();

echo "<hr /><strong>Example 7 (num rows, cols)</strong><br />Cols: {$cols}, Rows:


{$rows}<br />";

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

// Count with condition


$count2 = $db->countRows('table', "`date` = '".date("Y-m-d")."'");

echo "<hr /><strong>Example 8 (count rows)</strong><br />Count all: {$count}, Count


today: {$count2}<br />";
// 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
*/
// $db->countRows($table, $where = NULL)
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

// Example 9
// Array to insert
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 91

// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = '[email protected]';
// reserved values 'null', 'now()', 'curtime()', 'localtime()', 'localtime',
'utc_date()', 'utc_time()', 'utc_timestamp()'
$data['date'] = 'now()';

// $db->arrayToInsert( ... ) returns insert id


$insert_id = $db->arrayToInsert('table', $data);
echo "<hr /><strong>Example 9 (array to insert)</strong><br />Last insert id is:
{$insert_id}<br />";

// Array data
// [fealdname] = feald value
$data = array();
$data['firstname'] = 'Radovan';
$data['surname'] = 'Janjic';
$data['email'] = '[email protected]';
$data['date'] = 'now()';

// [fealdname] = feald value


$data2 = array();
$data2['firstname'] = 'Radovan';
$data2['surname'] = 'Janjic';
$data2['email'] = '[email protected]';
$data2['date'] = 'now()';

// $db->arrayToInsert( ... ) multirow returns TRUE on success


$db->arrayToInsert('table', array($data, $data2 /*, $data3 .... */ ));

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 92

// Returns next auto increment value


$auto_increment = $db->nextAutoIncrement('table');

echo "<hr /><strong>Example 10 (next auto increment)</strong><br>Next auto


increment id is: {$auto_increment}<br />";

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

$db->arrayToUpdate('table', $data, "`id` = {$insert_id}");


if ($db->affected) {
echo "<hr /><strong>Example 11 (array to update)</strong><br />Updated: {$db-
>affected} row(s).<br />";
}

// Array data
// [fealdname] = feald value
$data = array();
$data['id'] = 1; // key
$data['firstname'] = 'foo';
$data['surname'] = 'bar';
$data['email'] = '[email protected]';
$data['date'] = 'now()';

// [fealdname] = feald value


$data2 = array();
$data2['id'] = 2; // key
$data2['firstname'] = 'Radovana';
$data2['surname'] = 'Janjic';
$data2['email'] = '[email protected]';
$data2['date'] = 'now()';

// $db->arrayToUpdate( ... ) multirow returns TRUE on success


$db->arrayToUpdate('table', array($data, $data2 /*, $data3 .... */ ));

// More options
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 93

* @param string $where - MySQL WHERE Clause


* @param integer $limit - Limit offset
* @param resource $link - link identifier
* @return number of updated rows or false
*/
// $db->arrayToUpdate($table, $data, $where = NULL, $limit = 0, $link = 0)
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

// Example 12
// Delete row
///////////////////////////////////////////////////////////////////////////////////
////////
$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();

$db->deleteRow('table', "`id` = {$insert_id}");


if ($db->affected) {
echo "<hr><strong>Example 12 (delete row)</strong><br />Deleted: {$db-
>affected} row(s).<br />";
}
// 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
*/
// $db->deleteRow($table, $where = NULL, $limit = 0, $link = 0)
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 94

// Copy table (with data included)


$db->copyTable('table', 'table_copy');

// Copy table (with data included)


$db->copyTable('table', 'table_copy4');

// Copy table structure


$db->copyTable('table', 'table_copy2', FALSE);

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

// Truncate table (empty)


$db->truncateTable('table_copy2');

// Drop one table


$db->dropTable('table_copy4');
// Drop multiple tables
$db->dropTable(array('table_copy3', 'table_copy2'));

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 95

$db = MySQL_wrapper::getInstance(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);


$db->connect();
$db->logQueries = TRUE; // Default is FALSE, use TRUE only for debuging
$db->logErrors = TRUE; // This is useful to be TRUE!
$db->displayError = TRUE; // Default is FALSE, use TRUE only for debuging (security
reasons!)
$db->dateFormat = "Y-m-d H:i:s"; // Date / Time format for log
$db->logFilePath = 'log-mysql.txt'; // Log file
echo "<hr /><strong>Example 14 </strong><br>Loging queries and errors.<br />";
// Query for this function will be logged
$db->getColumns('table');
// This query has error

$db->query('SELECT * FROM `table` asfd!@#$');


$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 96

// 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
*/

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 97

// $db->importCSV2Table($file, $table, $delimiter = ',', $enclosure = '"', $escape


= '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\n')
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

// Import and update all data


$db->importUpdateCSV2Table('test_files/countrylist.csv', 'csv_to_table_test');

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 98

// Import and update all data


$db->importUpdateCSV2Table('test_files/countrylist.csv', 'csv_to_table_test', ',',
'"', '\\', 1, array(), 'file', '\r\n');
// More options
/** 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: ',')
* @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
*/
// $db->importUpdateCSV2Table($file, $table, $delimiter = ',', $enclosure = '"',
$escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine
= '\n')
// Close connection
$db->close();
///////////////////////////////////////////////////////////////////////////////////
////////

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

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 99

///////////////////////////////////////////////////////////////////////////////////
////////
$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('[email protected]');

$db->query("select * from asdf");


$db->query("select * from asdf2"); // this one will not be executed because
dieOnError = TRUE
// Close connection

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon


Chapter 12 - Source Code 100

$db->close();

PHP MySQL Wrapper Class Copyright © 2021, Bijesh Lal Nyachhyon

You might also like