Mysql + php database operations
Class DbQueryForMysql {
/**
* Maximum number of records returned by the select Method
*/
Const max_row_num= 1000;
/**
* Data Query Result set object
* @ Var object $ dataSet
*/
Public $ dataSet = NULL;
/**
* Data source object
* @ Var object $ ds
*/
Public $ ds = NULL;
/**
* The queried SQL statement
* @ Var string $ SQL
*/
Public $ SQL = '';
Public $ transCnt = 0;
/**
* Query mode. The value is OCI_COMMIT_ON_SUCCESS or OCI_DEFAULT.
* @ Var string $ excuteMode
*/
Public $ executeMode = 'oss _ COMMIT_ON_SUCCESS ';
/**
* Constructor
* @ Param object $ ds Database
* @ Param string $ SQL the SQL statement to be initialized and queried
*/
Function _ construct ($ ds = NULL, $ SQL = NULL ){
If (! $ Ds ){
$ This-> error (DbException: DB_UNCONNECTED, 'database also
Not connected. ');
} Else {
$ This-> ds = $ ds;
If ($ SQL ){
$ This-> open ($ SQL );
}
}
}
/**
* Release the memory occupied
* @ Param object $ dataSet: result set of the resource to be released
* @ Access public
*/
Public function close ($ dataSet = NULL ){
If ($ dataSet ){
@ Mysql_free_result ($ dataSet );
} Else {
@ Mysql_free_result ($ this-> dataSet );
$ This-> eof = false;
$ This-> recordCount = 0;
$ This-> recNo =-1;
}
}
/**
* Encrypt the $ pass database and return the encrypted value.
* @ Param string $ pass the string to be encrypted
* @ Return string
* @ Access public
*/
Public function encodePassword ($ pass ){
Return $ this-> getValue ("SELECT password ('$ pass') AS pass ");
}
/**
* Get the error message and error code
* @ Param integer $ queryResult Query Result
* @ Return array
* @ Access protected
*/
Protected function errorInfo ($ queryResult = NULL ){
$ Result ['message'] = @ mysql_error ($ this-> ds-> connect );
$ Result ['code'] = @ mysql_errno ($ this-> ds-> connect );
Return $ result;
}
/**
* Handle error messages
* @ Param string $ errorId error ID
* @ Param string $ error message
* @ Access protected
*/
Protected function error ($ errorId, $ errorMessage ){
Throw new DbException ($ errorMessage, $ errorId );
}
/**
* Execute SQL statements
* @ Param string $ SQL SQL statement
* @ Return object
* @ Param int $ rowFrom start row number, which starts from 1
* @ Param int $ rowTo end row number. The value 0 indicates
* @ Access public
* @ See DbQuery: open
*/
Public function execute ($ SQL = '', $ rowFrom = 0, $ rowTo =
Self: MAX_ROW_NUM, $ error = true ){
If ($ rowTo! = Self: MAX_ROW_NUM | $ rowFrom! = 0 ){
$ Nrows = $ rowTo-$ rowFrom + 1;
$ Start = $ rowFrom-1;
$ Start = ($ start> = 0 )? (Integer) $ start ).',':'';
$ SQL. = 'limit'. $ start. $ nrows;
}
// Echo $ SQL. '<br> ';
$ DataSet = @ mysql_query ($ SQL, $ this-> ds-> connect );
If (! $ DataSet & $ error ){
$ SqlError = $ this-> errorInfo ();
$ ErrorMessage = 'run [<B> <font color = "# FF0000"> '.
$ SQL
. '</Font> </B>] error! <Br> <font
Color = # FF0000> ['
. $ SqlError ['code']. ']:'
. $ SqlError ['message']. '</font> ';
$ This-> error (DbException: DB_QUERY_ERROR,
$ ErrorMessage );
}
Return $ dataSet;
}
/**
* Execute the SQL statement and save the result set to the attribute $ dataSet.
* @ Param string $ SQL SQL statement
* @ Param int $ rowFrom start row number, which starts from 1
* @ Param int $ rowTo end row number. The value 0 indicates
* @ Return object
* @ Access public
* @ See DbQuery: execute
*/
Public function open ($ SQL = '', $ rowFrom = 0, $ rowTo =
Self: MAX_ROW_NUM ){
$ This-> dataSet = $ this-> execute ($ SQL, $ rowFrom, $ rowTo );
$ This-> SQL = $ SQL;
Return $ this-> dataSet;
}
/**
* Split the field values of a row into an array.
* @ Param object $ dataSet result set
* @ Param integer $ resultType: return type, OCI_ASSOC, OCI_NUM, or
OCI_BOTH
* @ Return array
*/
Public function fetchRecord ($ dataSet = NULL, $ resultType = MYSQL_BOTH ){
$ Result = @ mysql_fetch_array ($ dataSet )? $ DataSet: $ this-
> DataSet, $ resultType );
Return $ result;
}
/**
* Obtain the number of fields
* @ Param object $ dataSet result set
* @ Return integer
*/
Public function getFieldCount ($ dataSet = NULL ){
Return mysql_num_fields ($ dataSet )? $ DataSet: $ this-
> DataSet );
}
/**
* Obtain the next record. Returns the record number. If it reaches the end of the record, FALSE is returned.
* @ Return integer
* @ Access public
* @ See getPrior ()
*/
Public function next (){
Return $ this-> fetchRecord ();
}
/**
* Obtain the current database time in the format of yyyy-mm-dd hh: mm: ss.
* @ Return string
* @ Access public
*/
Public function getNow (){
Return $ this-> getValue ('select NOW () AS dateOfNow ');
}
/**
* Retrieve data from the data table according to the SQL statement. Only the value of the first record is obtained,
* If the record contains only one field, only the field value is returned.
* If not found, FALSE is returned.
*
* @ Param string $ SQL SQL statement
* @ Return array
* @ Access public
*/
Public function getValue ($ SQL = ''){
$ DataSet = $ this-> execute ($ SQL, 1, 1 );
If ($ result = $ this-> fetchRecord ($ dataSet )){
$ FieldCount = $ this-> getFieldCount ($ dataSet );
$ This-> close ($ dataSet );
Return ($ fieldCount <= 1 )? $ Result [0]: $ result;
} Else {
Return false;
}
}
Public function getInsertId (){
Return $ this-> getValue ('select LAST_INSERT_ID ()');
}
Public function getSeq ($ seq = ''){
$ This-> execute ('in in TRANSACTION adodbseq ');
$ OK = $ this-> execute ("update $ seq with (tablock, holdlock)
Set id = id + 1 ", 0, self: MAX_ROW_NUM, false );
If (! $ OK ){
$ This-> execute ("create table $ seq (id float (53 ))");
$ OK = $ this-> execute ("insert into $ seq
(Tablock, holdlock) values (1) ", 0, self: MAX_ROW_NUM, false );
If (! $ OK ){
$ This-> execute ('rollback TRANSACTION
Adodbseq ');
Return false;
}
$ This-> execute ('commit TRANSACTION adodbseq ');
Return 1;
}
$ Num = $ this-> getValue ("select id from $ seq ");
$ This-> execute ('commit TRANSACTION adodbseq ');
Return $ num;
}
/**
* Returns true if the table exists.
* @ Param string $ tableName name of the table to be queried
* @ Return bool
* @ Access public
*/
Public function tableIsExists ($ tableName ){
$ Result = @ mysql_query ('select * FROM '. $ tableName .'
LIMIT 0, 1 ', $ this-> db-> connect );
Return $ result! = False;
}
/**
* Start transaction
* @ Access public
*/
Public function begin (){
$ This-> transCnt + = 1;
$ This-> execute ('in in TRAN ');
Return true;
}
/**
* Submit a transaction.
* @ Access public
*/
Public function commit (){
If ($ this-> transCnt ){
$ This-> transCnt-= 1;
}
$ This-> execute ('commit TRAN ');
Return true;
}
/**
* Roll back a transaction
* @ Access public
*/
Public function rollback (){
If ($ this-> transCnt ){
$ This-> transCnt-= 1;
}
$ This-> execute ('rollback TRAN ');
Return true;
}
/**
* Insert a record
* @ Param string $ tableName table name
* @ Param array $ fieldArray field array
* @ Param string $ whereForUnique uniqueness Condition
* @ Return int
* @ Access public
*/
Public function insert ($ tableName, $ fieldArray, $ whereForUnique =
NULL ){
If (! $ TableName |! $ FieldArray |! Is_array ($ fieldArray )){
Throw new Exception ('parameter $ tableName or $ fieldArray
The value of is invalid! ');
}
If ($ whereForUnique ){
$ Where = 'where'. $ whereForUnique;
$ IsExisted = $ this-> getValue ('select COUNT (*) from'
. $ TableName. $ where );
If ($ isExisted ){
Throw new DbException ('record already exists! ',
DbException: DB_RECORD_IS_EXISTED );
}
}
$ FieldNameList = array ();
$ FieldValueList = array ();
Foreach ($ fieldArray as $ fieldName => $ fieldValue ){
If (! Is_int ($ fieldName )){
$ FieldNameList [] = $ fieldName;
$ FieldValueList [] = '''. $ fieldValue.
''';
}
}
$ FieldName = implode (',', $ fieldNameList );
$ FieldValue = implode (',', $ fieldValueList );
$ SQL = 'insert'. $ tableName .'('
. $ FieldName. ') VALUES ('.
$ FieldValue .')';
Return $ this-> execute ($ SQL );
}
/**
* Update a record
* @ Param string $ tableName table name
* @ Param array $ fieldArray field array
* @ Param string $ whereForUpdate query Condition
* @ Param string $ whereForUnique uniqueness Condition
* @ Return int
* @ Access public
*/
Public function update ($ tableName, $ fieldArray,
$ WhereForUpdate = NULL, $ whereForUnique = NULL ){
If (! $ TableName |! $ FieldArray |! Is_array ($ fieldArray )){
Throw new Exception ('parameter $ tableName or $ fieldArray
The value of is invalid! ');
}
If ($ whereForUnique ){
$ Where = 'where'. $ whereForUnique;
$ IsExisted = $ this-> getValue ('select COUNT (*) from'
. $ TableName. $ where );
If ($ isExisted ){
Throw new DbException ('record already exists! ',
DbException: DB_RECORD_IS_EXISTED );
}
}
$ FieldNameValueList = array ();
Foreach ($ fieldArray as $ fieldName => $ fieldValue ){
If (! Is_int ($ fieldName )){
$ FieldNameValueList [] = $ fieldName. '= ''.
$ FieldValue .''';
}
}
$ FieldNameValue = implode (',', $ fieldNameValueList );
If ($ whereForUpdate ){
$ WhereForUpdate = 'where'. $ whereForUpdate;
}
$ SQL = 'update'. $ tableName
. 'Set'. $ fieldNameValue.
$ WhereForUpdate;
Return $ this-> execute ($ SQL );
}
/**
* Select a record
* @ Param string $ SQL statement
* @ Param string $ dataFormat returns the data format, Value
"Array", "hashmap", "hashmap_str", "dataset"
* @ Param int $ rowFrom start row number, which starts from 1
* @ Param int $ rowTo end row number. The value 0 indicates
* @ Result array
* @ Access public
*/
Public function select ($ SQL, $ dataFormat = 'array', $ rowFrom = 0,
$ RowTo = self: MAX_ROW_NUM ){
$ DataSet = $ this-> execute ($ SQL, $ rowFrom, $ rowTo );
Switch ($ dataFormat ){
Case 'array': // array
$ Result = array ();
$ IsMultiField = ($ this-> getFieldCount ($ dataSet)>
1 );
$ I = 0;
While ($ data = $ this-> fetchRecord ($ dataSet )){
$ Result [$ I] = ($ isMultiField )? $ Data:
$ Data [0];
$ I ++;
}
$ This-> close ($ dataSet );
Break;
Case 'hashmap': // hash
$ Result = array ();
While ($ data = $ this-> fetchRecord ($ dataSet )){
$ Result [$ data [0] = $ data [1];
}
$ This-> close ($ dataSet );
Break;
Case 'hashmap _ str': // hash string
$ Result = array ();
While ($ data = $ this-> fetchRecord ($ dataSet,
OCI_NUM )){
$ Result [] = $ data [0]. '='. $ data [1];
}
$ Result = implode ('|', $ result );
$ This-> close ($ dataSet );
Break;
Default: // dataset. When the returned data format is dataset, select
The function of the method is the same as that of the execute method.
$ Result = $ dataSet;
}
Return $ result;
}
/**
* Returns the maximum value.
* @ Param string $ tableName table name
* @ Param string $ idField field name
* @ Param string $ where query Condition
* @ Return int
* @ Access public
*/
Public function getMax ($ tableName, $ idField, $ where = NULL ){
$ Where = ($ where )? ('Where'. $ WHERE ):'';
Return $ this-> getValue ('select MAX ('. $ idField.') from'
. $ TableName. $ where );
}
}
?>