Mysql+php Database Operations Class
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 objects
* @var Object $ds
*/
Public $ds = NULL;
/**
* SQL statement for query
* @var String $sql
*/
Public $sql = ';
Public $transCnt = 0;
/**
* The mode of executing the query, the value is oci_commit_on_success or Oci_default
* @var String $excuteMode
*/
Public $executeMode = ' oci_commit_on_success ';
/**
* Constructor
* @param Object $ds Database
* @param string $sql The SQL statement to initialize the query
*/
function __construct ($ds =null, $sql =null) {
if (! $ds) {
$this->error (dbexception::D b_unconnected, ' database also
Not connected. ');
} else {
$this->ds = $ds;
if ($sql) {
$this->open ($sql);
}
}
}
/**
* Free up the memory occupied
* @param object $dataSet The result set of the resource that needs to be freed
* @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;
}
}
/**
* Database encryption for $pass, returns the value after encryption
* @param string $pass strings to encrypt
* @return String
* @access Public
*/
Public Function Encodepassword ($pass) {
return $this->getvalue ("Select Password (' $pass ') as pass");
}
/**
* Get error message and error code
* @param integer $queryResult query results
* @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;
}
/**
* Error Information Processing
* @param string $errorId Error ID
* @param string $errorMessage error message
* @access protected
*/
protected function Error ($ERRORID, $errorMessage) {
throw new Dbexception ($errorMessage, $errorId);
}
/**
* Execute SQL statement
* @param string $sql SQL statement
* @return Object
* @param int $rowFrom start line number, starting from 1
* @param int $rowTo end line number, and a value of 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 = ' Execute [<b><font color= ' #FF0000 ' > '.
$sql
. ' </font></b>] An error! <br> <font
color= #FF0000 > ['
. $sqlError [' Code ']. ']: '
. $sqlError [' message ']. ' </font> ';
$this->error (dbexception::D b_query_error,
$errorMessage);
}
return $dataSet;
}
/**
* Execute SQL statement, result set saved to attribute $dataset
* @param string $sql SQL statement
* @param int $rowFrom start line number, starting from 1
* @param int $rowTo end line number, and a value of 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 a row of field values 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;
}
/**
* Get the number of fields
* @param object $dataSet result set
* @return Integer
*/
Public Function GetFieldCount ($dataSet = NULL) {
Return Mysql_num_fields ($dataSet)? $dataSet: $this-
>dataset);
}
/**
* Get the next record. Returns the record number, or False if the end of the record is returned
* @return Integer
* @access Public
* @see Getprior ()
*/
Public function next () {
return $this->fetchrecord ();
}
/**
* Get the current database time, the format is: Yyyy-mm-dd hh:mm:ss
* @return String
* @access Public
*/
Public Function Getnow () {
return $this->getvalue (' SELECT now () as Dateofnow ');
}
/**
* Take the data from the datasheet according to the SQL statement, take the value of the first record only,
* If there is only one field in the record, only the field value is returned.
* Return FALSE not found
*
* @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 (' BEGIN 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 with
(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;
}
/**
* Whether the table exists, returns true
* @param string $tableName the name of the table to query
* @return BOOL
* @access Public
*/
Public Function tableisexists ($tableName) {
$result = @mysql_query (' SELECT * from '. $tableName. '
LIMIT 0,1 ', $this->db->connect);
return $result!==false;
}
/**
* Start a transaction
* @access Public
*/
Public function begin () {
$this->transcnt + 1;
$this->execute (' BEGIN 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 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
* @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 is not legal! ');
}
if ($whereForUnique) {
$where = ' where '. $whereForUnique;
$isExisted = $this->getvalue (' SELECT COUNT (*) from '
. $tableName. $where);
if ($isExisted) {
throw new Dbexception (' record already exists! ',
Dbexception::D b_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 into '. $tableName. '('
. $fieldName. ') VALUES ('.
$fieldValue. ')';
return $this->execute ($sql);
}
/**
* Update a record
* @param string $tableName table name
* @param array $fieldArray field
* @param string $whereForUpdate query criteria
* @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 is not legal! ');
}
if ($whereForUnique) {
$where = ' where '. $whereForUnique;
$isExisted = $this->getvalue (' SELECT COUNT (*) from '
. $tableName. $where);
if ($isExisted) {
throw new Dbexception (' record already exists! ',
Dbexception::D b_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 SQL statement
* @param string $dataFormat Returns the data format, the value
There are "array", "HashMap", "Hashmap_str", "DataSet"
* @param int $rowFrom start line number, starting from 1
* @param int $rowTo end line number, and a value of 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 list
$result = Array ();
while ($data = $this->fetchrecord ($dataSet)) {
$result [$data [0]] = $data [1];
}
$this->close ($dataSet);
Break
Case ' hashmap_str '://Hash List string
$result = Array ();
while ($data = $this->fetchrecord ($dataSet,
Oci_num)) {
$result [] = $data [0]. '=' . $data [1];
}
$result = implode (' | ', $result);
$this->close ($dataSet);
Break
Default://dataset DataSet, when the return data format is a dataset, select
Method has the same functionality as 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 criteria
* @return int
* @access Public
*/
Public Function Getmax ($tableName, $idField, $where = NULL) {
$where = ($where)? (' WHERE '. $where): ';
return $this->getvalue (' SELECT MAX ('. $idField. ') from '
. $tableName. $where);
}
}
?>