Php method for encapsulating MySQL classes based on a single case pattern

Source: Internet
Author: User
This article mainly introduces PHP based on a single case model package MySQL class, combined with a complete example of PHP using a single case pattern package MySQL class definition and use method, the need for friends can refer to the following

Specific as follows:

Class:


<?phpheader ("Content-type:text/html;charset=utf-8");//Package A class/* to master the necessary conditions for satisfying a singleton pattern (1) Private constructor-to prevent the instantiation of an object with the New keyword outside the class (2  Private member properties-to prevent the introduction of this object-holding property outside of the class (3) Private cloning method-to prevent another object from being genetic through clone (4) public static method-in order to let the user instantiate the object's Operation */class db{//Three private/private static properties  private static $dbcon =false;   Private constructor Method __construct () {$dbcon = @mysql_connect ("localhost", "root", "root");   mysql_select_db ("Small2", $dbcon) or Die ("Mysql_connect error");  mysql_query ("Set names UTF8");    }//Private Clone Method __clone () {}//Common static method public static function Getintance () {if (self:: $dbcon ==false) {   Self:: $dbcon =new self;  } return Self:: $dbcon;    }//Print data public function p ($arr) {echo "<pre>";    Print_r ($arr);  echo "</pre>";    } public Function V ($arr) {echo "<pre>";    Var_dump ($arr);  echo "</pre>";   }//Execute statement Public Function query ($sql) {$query =mysql_query ($sql);  return $query; /** * Query a field * @param * @return string or int */Public Function GetOne ($sql) {$query =$this->query ($sql);  Return mysql_result ($query, 0);   }//Gets a row of records, return array of one-dimensional array public function GetRow ($sql, $type = "Assoc") {$query = $this->query ($sql);   if (!in_array ($type, Array ("Assoc", ' array ', "Row"))) {die ("mysql_query error");   } $funcname = "Mysql_fetch_". $type;  Return $funcname ($query); }//Get a record, the precondition gets a record through the resource public function Getformsource ($query, $type = "Assoc") {if (!in_array ($type, Array ("Assoc", "  Array "," Row ")) {die (" mysql_query error ");  } $funcname = "Mysql_fetch_". $type;  Return $funcname ($query);   }//Get multiple data, two-dimensional array public function getAll ($sql) {$query = $this->query ($sql);   $list =array ();   while ($r = $this->getformsource ($query)) {$list []= $r;  } return $list;  }//Get last Record ID public function Getinsertid () {return mysql_insert_id (); }/** * defines how to add data * @param string $table table name * @param string Orarray $data [data] * @return int the newly added ID */Publ   IC function Insert ($table, $data) {//Iterate through the array to get the value of each field and field $key _str= '; $v _stR= ";   foreach ($data as $key = + $v) {if (empty ($v)) {die ("error");      The value of the//$key is the value of one field per field S $key _str.= $key.   $v _str.= "' $v ',";   } $key _str=trim ($key _str, ', ');   $v _str=trim ($v _str, ', ');   Determines whether the data is empty $sql = "INSERT INTO $table ($key _str) VALUES ($v _str)"; $this->query ($sql); Returns the last increment of the operation to generate the ID value of return mysql_insert_id (); }/* * Delete a data method * @param1 $table, $where =array (' id ' = ' 1 ') Table name condition * @return The number of rows affected * */Public Function Deleteone ($tab Le, $where) {if (Is_array ($where)) {foreach ($where as $key = $val) {$condition = $key. '      = '. $val;    }} else {$condition = $where;    } $sql = "Delete from $table where $condition";    $this->query ($sql);  Returns the number of rows affected return mysql_affected_rows (); }/* * Delete multiple data methods * @param1 $table, $where table name condition * @return The number of rows affected */Public function deleteAll ($table, $where) {if ( Is_array ($where)) {foreach ($where as $key = = $val) {if (Is_array ($val)) {$condition = $key. ' In ('. Implode (', ', $val) ') '; } else {$condition = $key.        ' = '. $val;    }}}} else {$condition = $where;    } $sql = "Delete from $table where $condition";    $this->query ($sql);  Returns the number of rows affected return mysql_affected_rows (); }/** * [Modify Operation description] * @param [type] $table [table name] * @param [type] $data [data] * @param [type] $where [condition] * @retur  n [Type] */Public Function update ($table, $data, $where) {//Iterate through the array to get the value of each field and field $str = ';  foreach ($data as $key + $v) {$str. = "$key = ' $v ',";  } $str =rtrim ($str, ', ');  Modify the SQL statement $sql = "Update $table set $str where $where";  $this->query ($sql); Returns the number of rows affected return mysql_affected_rows (); }}?>

Test:

MySQL test//$db =db::getintance ();//var_dump ($db);/* $sql = "SELECT * from acticle"; $list = $db->getall ($sql); $db- >p ($list); *//* $sql = "SELECT * from acticle where acticle_id=95"; $list = $db->getrow ($sql); $db->p ($list); *//*$ Sql= "SELECT title from Acticle"; $list = $db->getone ($sql); $db->p ($list); *///$list = $db->insert ("Users", $_ POST);//$del = $db->deleteone ("Users", "id=26"),//$del = $db->deleteall ("Users", "ID in (23,24)"),//$up = $db Update ("Users", $_post, "id=27");//$id = $db->getinsertid ();//print_r ($id);

Summary: The above is the entire content of this article, I hope to be able to help you learn.

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.