PHP Data operation class & lt ;
? Php/** + ---------------------------------------------------------- * Mysql operation class + -----------------------------------------------
PHP Data operation class
cachePath . strtoupper(md5($fileName)).".".$this->cacheFileExt;
$this->cacheFileName=$cacheFileName;
}
/*
* Generate cache file name based on current dynamic file
*/
Function getCacheFileName() {
Return $this->cacheFileName;
}
/**
* Connect to the database
*
* @access public
* @param array $db database configuration
* @return resource database connection identifier
*/
Public function connect($db){
/ / Use the different functions to connect to the database according to the configuration
$db['host'] = isset($db['port']) ? $db['host'].':'.$db['port']: $db['host'];
$db['char'] = isset($db['char']) ? $db['char']: $this->dbCharset;
$func = $db['pconnect'] ? 'mysql_pconnect' : 'mysql_connect';
$this->link = $func($db['host'], $db['user'], $db['pwd']);
Mysql_select_db($db['database'], $this->link);
Mysql_query("SET NAMES '{$db['char']}'");
$this->cachePath = isset($db['cachepath']) ? $db['cachepath']: $this->cachePath;
Return $this->link;
}
/**
* Query a record that meets the criteria
*
* @access public
* @param string $where query condition
* @param string $field query field
* @param string $table table
* @return mixed Eligible records
*/
Public function find($where = NULL, $field = '*', $table = ''){
Return $this->findAll($where = NULL, $field = '*', $table = '', FALSE);
}
/**
* Query all records that meet the criteria
*
* @access public
* @param string $where query condition
* @param string $field query field
* @param string $table table
* @return mixed Eligible records
*/
Public function findAll($where = NULL, $field = '*', $table = '', $all = TRUE){
$this->options['where'] = is_null($where) ? @$this->options['where']: $where;
$this->options['field'] = isset($this->options['field']) ? $this->options['field']: $field;
$this->options['table'] = $table == '' ? $this->table: $table;
$sql = "SELECT {$this->options['field']} FROM `{$this->options['table']}` ";
$sql .= isset($this->options['join']) ? ' LEFT JOIN '.$this->options['join']: '';
$sql .= isset($this->options['where']) ? ' WHERE '.$this->options['where']: '';
$sql .= isset($this->options['group']) ? ' GROUP BY '.$this->options['group']: '';
$sql .= isset($this->options['having']) ? ' HAVING '.$this->options['having']: '';
$sql .= isset($this->options['order']) ? ' ORDER BY '.$this->options['order']: '';
$sql .= isset($this->options['limit']) ? ' LIMIT '.$this->options['limit']: '';
$this->sql = $sql;
$row = NULL;
/ / If the cache is enabled, then the data is retrieved in the re-cache
If ($this->cache === TRUE){
$this->setCacheFileName($this->sql);
$row = $this->readCache();
}
/ / If the read fails, or the cache is not enabled
If (is_null($row)){
$result = $this->query();
$row = $all === TRUE ? $this->fetchAll($result): $this->fetch($result);
/ / If the cache is turned on, then write
If ($this->cache === TRUE){
$this->writeCache($row);
}
$this->options = array();
}
Return $row;
}
/**
* Read all records in the result set into an array
*
* @access public
* @param resource $result result set
* @return array
*/
Public function fetchAll($result = NULL){
$rows = array();
While ($row = $this->fetch($result)){
$rows[] = $row;
}
Return $rows;
}
/**
* Read a row of records in the result set into an array
*
* @access public
* @param resource $result result set
* @param int $type return type, 1 is an array, 2 is an object
* @return mixed Returns according to the return type
*/
Public function fetch($result = NULL, $type = NULL){
$result = is_null($result) ? $this->result: $result;
$type = is_null($type) ? $this->returnType: $type;
$func = $type === 1 ? 'mysql_fetch_assoc' : 'mysql_fetch_object';
Return $func($result);
}
/**
* Execute SQL commands
*
* @access public
* @param string $sql SQL command
* @param resource $link database connection identifier
* @return mixed database result set
*/
Public function query($sql = '', $link = NULL){
$sql = empty($sql) ? $this->sql: $sql;
$link = is_null($link) ? $this->link: $link;
$this->result = mysql_query($sql, $link);
If (is_resource($this->result)){
Return $this->result;
}
/ / If the execution of the SQL error, then throw an exception
Exit('Mysql error:'.$this->getError());
}
/**
* Execute SQL commands
*
* @access public
* @param string $sql SQL command
* @param resource $link database connection identifier
* @return bool Whether it succeeded
*/
Public function execute($sql = '', $link = NULL){
$sql = empty($sql) ? $this->sql: $sql;
$link = is_null($link) ? $this->link: $link;
If (mysql_query($sql, $link)){
Return TRUE;
}
Return FALSE;
}
/**
* Insert record
*
* @access public
* @param array $data Inserted record, format: array('field name'=>'value', 'field name'=>'value');
* @param string $table table name
* @return bool current record id
*/
Public function add($data, $table = NULL){
$table = is_null($table) ? $this->table: $table;
$sql = "INSERT INTO `{$table}`";
$fields = $values = array();
$field = $value = '';
/ / Traverse the record, format the field name and value
Foreach($data as $key => $val){
$fields[] = "`{$table}`.`{$key}`";
$values[] = is_numeric($val) ? $val : "'{$val}'";
}
$field = join(',', $fields);
$value = join(',', $values);
Unset($fields, $values);
$sql .= "({$field}) VALUES({$value})";
$this->sql = $sql;
$this->execute();
Return $this->insertId();
}
/**
* Delete Record
*
* @access public
* @param string $where condition
* @param string $table table name
* @return bool affects the number of rows
*/
Public function delete($where = NULL, $table = NULL){
$table = is_null($table) ? $this->table: $table;
$where = is_null($where) ? @$this->options['where']: $where;
$sql = "DELETE FROM `{$table}` WHERE {$where}";
$this->sql = $sql;
$this->execute();
Return $this->affectedRows();
}
/**
* update record
*
* @access public
* @param array $data Updated data Format: array('field name' => value);
* @param string $where update condition
* @param string $table table name
* @return bool How many pieces of information
*/
Public function update($data, $where = NULL, $table = NULL){
$table = is_null($table) ? $this->table: $table;
$where = is_null($where) ? @$this->options['where']: $where;
$sql = "UPDATE `{$table}` SET ";
$values = array();
Foreach($data as $key => $val){
$val = is_numeric($val) ? $val : "'{$val}'";
$values[] = "`{$table}`.`{$key}` = {$val}";
}
$value = join(',', $values);
$this->sql = $sql.$value." WHERE {$where}";
$this->execute();
Return $this->affectedRows();
}
/**
* Read cache
*
* @access public
* @return mixed Returns the cached content if the read succeeds, otherwise returns NULL
*/
Protected function readCache(){
$file = $this->getCacheFileName();
If (file_exists($file)){
//Cache expired
If ((filemtime($file) + $this->cacheLimitTime) < time()){
@unlink($file);
Return NULL;
}
If (1 === $this->returnType){
$row = include $file;
}
Else{
$data = file_get_contents($file);
$row = unserialize($data);
}
Return $row;
}
Return NULL;
}
/**
* Write cache
*
* @access public
* @param mixed $data cache content
* @return bool Whether to write successfully
*/
Public function writeCache($data){
$file = $this->getCacheFileName();
If ($this->makeDir(dirname($file))){
If (1 === $this->returnType){
$data = '';
}else{
$data = serialize($data);
}
}
Return file_put_contents($file, $data);
}
/*
* Clear cache file
* string $fileName specifies the file name (including function) or all (all)
* Return: clear successfully returns true, otherwise returns false
*/
Function clearCache( $fileName = "all" ) {
If( $fileName != "all" ) {
If( file_exists( $fileName ) ) {
Return @unlink( $fileName );
}else return false;
}
If ( is_dir( $this->cachePath ) ) {
If ( $dir = @opendir( $this->cachePath ) ) {
While ( $file = @readdir( $dir ) ) {
$check = is_dir( $file );
If ( !$check )
@unlink( $this->cachePath . $file );
}
@closedir( $dir );
Return true;
}else{
Return false;
}
}else{
Return false;
}
}
/*
* Continuous construction directory
* string $dir directory string
* int $mode permission number
* Back: successfully created or all built back true, other methods return false
*/
Function makeDir( $dir, $mode = "0777" ) {
If( ! $dir ) return 0;
$dir = str_replace( "\\", "/", $dir );
$mdir = "";
Foreach( explode( "/", $dir ) as $val ) {
$mdir .= $val."/";
If( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
If( ! file_exists( $mdir ) ) {
If(!@mkdir( $mdir, $mode )){
Return false;
}
}
}
Return true;
}
/ / Automatically load the function to achieve special operations
Public function __call($func, $args)
{
If(in_array($func, array('field', 'join', 'where', 'order', 'group', 'limit', 'having')))
{
$this->options[$func] = array_shift($args);
Return $this;
} elseif($func === 'table'){
$this->options['table'] = array_shift($args);
$this->table = $this->options['tAble'];
Return $this;
}
/ / If the function does not exist, throw an exception
Exit('Call to undefined method Db::' . $func . '()');
}
//-------------------------------------------
/ / Returns the number of rows affected by the previous operation
Public function affectedRows($link = null){
$link = is_null($link) ? $this->link : $link;
Return mysql_affected_rows($link);
}
/ / Returns the id of the last operation record
Public function insertId($link = null){
$link = is_null($link) ? $this->link : $link;
Return mysql_insert_id($link);
}
/ / Clear the result set
Public function free($result = null){
$result = is_null($result) ? $this->result : $result;
Return mysql_free_result($result);
}
/ / Return error message
Public function getError($link = NULL){
$link = is_null($link) ? $this->link : $link;
Return mysql_error($link);
}
/ / Return error number
Public function getErrno($link = NULL){
$link = is_null($link) ? $this->link : $link;
Return mysql_errno($link);
}
}
?>
? Call method:
Connect($config); //Incoming configuration, connecting to the database, $link is the connection identifier
$rows = $db->table('test')->field('*')->order('id DESC')->limit(0, 10)->findAll();
/ / The above operation, equivalent to executing the SQL command: SELECT * FROM test ORDER BY id DESC LIMIT 0, 10;
Print_r($db->getCacheFileName());
//$db->clearCache($db->getCacheFileName());
//$db->clearCache();
// The effect of the execution is the same as above, but there is one more cache method, which caches the query cache() with three parameters, cache (cache name, valid time, cache path); cache name defaults to use md5 (SQL Command) is the name, the effective time defaults to 1 minute, and the cache path can be configured when connecting to the database.
/ / Next to insert a record
$data = array(
'name' => 'xiaokai',
'pass' => '123456',
);
$db->add($data);
// This inserts a record. Note that the format of $data is array('field name 1' => 'value 1', 'field name 2' => 'value 2', .....);
/ / Equivalent to executing the SQL command: INSERT INTO test (`name`, `pass`) VALUES ('xiaokai', '123456');
//Friends may be surprised, the add function does not pass in the table name, why do you execute such SQL commands?
/ / In fact, the above query has used the $db->table ('test') method, the table name has been passed here, so you do not need to specify the table name in the operation.
/ / There is a delete to delete, below to delete
$db->delete('id = 10');
/ / This deletes the record with id 10 in the test table
/ / Equivalent to executing the SQL command: DELETE FROM test WHERE id = 10;
/ / Here is the same as there is no incoming table name
/ / Construct the array below, and then update a record
$data = array(
'name' => '123456',
'pass' => 'xiaokai',
);
$db->update($data, 'id = 10');
//This will update the record with id 10
/ / Equivalent to executing the SQL command: UPDATE test set name = '123456', pass = 'xiaokai' WHERE id = 10;