PHP Data Manipulation types

Source: Internet
Author: User
Tags pconnect
PHP Data Manipulation Classes
 CachePath. Strtoupper (MD5 ($fileName)). ".".    $this->cachefileext; $this->cachefilename= $cacheFileName;    }/* * Generate cache file names based on current dynamic files */function getcachefilename () {return $this->cachefilename; /** * Connect to Database * * @access public * @param array $db Database configuration * @return Resource data Library Connection Identity */Public Function connect ($DB) {//use different functions according to configuration to connect to database $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 matches the criteria * * @access public * @param      String $where Query Criteria * @param string $field query field * @param string $table table * @retur N Mixed Qualifying record */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 conditions * @param St Ring $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 ($wher e)?        @ $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[' have ']: '; $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 turned on, then the cache gets the data if ($this->cache = = = TRUE) {$this->setcachefilename ($this->sql);        $row = $this->readcache ();            }//If the read fails, or if the cache is not turned on (Is_null ($row)) {$result = $this->query (); $row = $all = = = TRUE?            $this->fetchall ($result): $this->fetch ($result); If the cache is turned on, write if ($tHis->cache = = = TRUE) {$this->writecache ($row);        } $this->options = Array ();    } return $row;    }/** * Reads all the records in the result set into the 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; }/** * Reads a row from the result set into the array * * @access public * @param resource $result result set * @param int $ty PE return type, 1 for array, 2 for object * @return Mixed returns */Public function fetch based on return type ($result = NULL, $type = N        ULL) {$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 command * * @access public * @param      string $sql SQL command * @param resource $link Database connection identity * @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 there is an error executing SQL, throw an exception exit (' Mysql Error:  '. $this->geterror ()); /** * Execute SQL command * * @access public * @param string $sql SQL command * @param resou RCE $link Database Connection identity * @return BOOL executed successfully */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 = ";         Iterate through the record, format the field name with the 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 * @re turn bool affects 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 messages are affected */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 NULL if the read successfully returns the cached content */protected        function Readcache () {$file = $this->getcachefilename ();                if (file_exists ($file)) {//cache expires 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 the write succeeds */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 Specify file name (with function) or all * return: Clear successfully returns true, Reverse 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 directory * String $dir directory String * int $mode Permission number * return: Successfully created or all built returns True, other methods return False */function MakeDir ($dir, $m Ode = "0777") {if (! $dir) return 0; $dir = str_replace ("\ \", "/", $dir); $mdir = ""; foreach (Explode ("/", $dir) as $v AL) {$mdir. = $val. "  /"; if ($val = =": "| | $val = =". "| | Trim ($val) = =" ") continue; if (! file_exists ($mdir)) {if (! @mkdir ($mdir, $mode)) {return false;}}} ReTurn true;} Auto-load function for 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 last operation Public Function affectedrows ($link = null) {$link = Is_null ($link)?    $this->link: $link; return mysql_affected_rows ($link);         }//Returns the ID of the last Action record public function insertid ($link = null) {$link = Is_null ($link)? $this->link: $link;    Return mysql_insert_id ($link);        }//Empty 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);        }//Returns the error number public function Geterrno ($link = NULL) {$link = Is_null ($link)? $this->link: $link;    Return Mysql_errno ($link); }}?>

? Call Method:

 Connect ($config); Incoming configuration, connection database, $link for connection identity $rows = $db->table (' Test ')->field (' * ')->order (' id DESC ')->limit (0, ten) FindAll ();//The above operation, equivalent to execute SQL command: SELECT * FROM Test ORDER by ID DESC LIMIT 0, 10;print_r ($db->getcachefilename ());//$db-& Gt;clearcache ($db->getcachefilename ());//$db->clearcache ();//The effect of execution is the same as above, but a cache method is also cached for this query caches () There are three parameters, cache (buffer name, valid time, cache path);   The cache name defaults to the name using the MD5 (SQL command), the valid time default is 1 minutes, the cache path can be configured when connecting to the database//below to insert a record $data = Array (' name ' = ' Xiaokai ', ' Pass ' = ' 123456 ',); $db->add ($data);//This inserts a record note here $data format is array (' field name 1 ' = ' = ' value 1 ', ' field name 2 ' = = ' value 2 ', ...); /equivalent to execute 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 a SQL command? In fact, the above query has already used the $db->table (' Test ') method, here has passed the table name, so the operation will not need to specify the table name.//There is a delete, the following to delete $db->delete (' id = 10 ');// This removes the record with ID 10 in the test table//equivalent to the Execute SQL command: Delete from test where id = 10;//Here is the same as no incoming table name//The following constructs an array, and then updates a record $data = Array (' N  Ame= ' 123456 ', ' pass ' = ' Xiaokai ',); $db->update ($data, ' id = 10 ');//This will update the record with ID 10//equivalent to execute SQL command: Update te  St Set name = ' 123456 ', pass = ' Xiaokai ' where id = 10;

?

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.