PHP Encapsulation of Mysqli class complete instance _php technique

Source: Internet
Author: User

This example describes the Mysqli class in PHP encapsulation. Share to everyone for your reference, specific as follows:

Class:

<?php header (' Content-type:text/html;charset=utf-8 '); /* grasp the necessary conditions for a singleton pattern (1) Private construction method-to prevent the use of the new keyword to instantiate objects (2) Private member properties outside the class-in order to prevent the introduction of a private clone method of the property (3) that holds the object outside the class-to prevent another object from being genetic through the clone (4)
  Publicly-owned static methods-to allow the user to instantiate the object's operation/class connectmysqli{//private property private static $dbcon =false;
  Private $host;
  Private $port;
  Private $user;
  Private $pass;
  Private $db;
  Private $charset;
  Private $link; Private construction Method Private function __construct ($config =array ()) {$this->host = $config [' Host ']? $config [' Host ']: ' Local
    Host '; $this->port = $config [' Port ']?
    $config [' Port ']: ' 3306 '; $this->user = $config [' User ']?
    $config [' User ']: ' Root '; $this->pass = $config [' Pass ']?
    $config [' Pass ']: ' Root '; $this->db = $config [' db ']?
    $config [' DB ']: ' small2 '; $this->charset=isset ($arr [' CharSet '])?
    $arr [' CharSet ']: ' UTF8 ';
    Connect database $this->db_connect ();
    Select Database $this->db_usedb ();
   Sets the character set $this->db_charset (); }//Connection database Private function Db_cOnnect () {$this->link=mysqli_connect ($this->host. ': '. $this->port, $this->user, $this->pass);
      if (! $this->link) {echo "Database connection failed <br>"; echo "Error Encoding". Mysqli_errno ($this->link). "
      <br> "; echo "error message". Mysqli_error ($this->link). "
      <br> ";
    Exit
    }//Set the character set Private function Db_charset () {mysqli_query ($this->link, "set names {$this->charset}");
   //Select database Private Function Db_usedb () {mysqli_query ($this->link, "Use {$this->db}");
   }//Private clone Private Function __clone () {die (' clone is not allowed ');
     }//Common static method public static function Getintance () {if (self:: $dbcon ==false) {self:: $dbcon =new self;
   Return self:: $dbcon;
     }//Execute SQL statement method public Function query ($sql) {$res =mysqli_query ($this->link, $sql);
      if (! $res) {echo "SQL statement execution failed <br>"; echo "Error encoding is". Mysqli_errno ($this->link).
      <br> "; echo "error message is". Mysqli_eRror ($this->link). "
     <br> ";
   return $res;
      ///Print data public function p ($arr) {echo <pre>;
      Print_r ($arr);
    echo "</pre>";
      The Public Function V ($arr) {echo <pre>;
      Var_dump ($arr);
    echo "</pre>";
    //Get the last Record ID public function Getinsertid () {return mysqli_insert_id ($this->link); /** * Query for a field * @param * @return string or int */Public Function GetOne ($sql) {$query = $this-
      >query ($sql);
    Return Mysqli_free_result ($query);
     //Get a row of records, return array one-dimensional array public function GetRow ($sql, $type = "Assoc") {$query = $this->query ($sql);
     if (!in_array ($type, Array ("Assoc", "Array", "Row"))) {die ("Mysqli_query error");
     $funcname = "Mysqli_fetch_". $type;
    Return $funcname ($query); //Get a record, the precondition gets a record from the resource the public function Getformsource ($query, $type = "Assoc") {if!in_array ($type, Array ("Assoc "," Array, "row)) {die ("Mysqli_query error");
    $funcname = "Mysqli_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; /** * Defines methods for adding data * @param string $table table name * @param string Orarray $data [data] * @return int Latest Additions
     ID */Public Function Insert ($table, $data) {//traversal array, 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 corresponding value of each field S field $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 to do produces the ID value return $this->getinsertid (); } * * Delete a data method *param1 $table, $where =array (' id ' => ' 1 ') Table name condition * @return The number of rows affected */Public function Deleteone ($table, $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 Mysqli_affected_rows ($this->link); * * * Delete multiple data methods * @param1 $table, $where table name condition * @return Affected number of rows/Public function DeleteAll ($tabl
            E, $where) {if (Is_array ($where)) {foreach ($where as $key => $val) {if (Is_array ($val)) {
          $condition = $key. ' 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 MysQli_affected_rows ($this->link);  /** * [Modify Operation description] * @param [type] $table [table name] * @param [type] $data [data] * @param [type] $where
    [Condition] * @return [type]/Public function update ($table, $data, $where) {//traverse 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 Mysqli_affected_rows ($this->link);

 }}?>

Usage test:

Mysqli Test
$db =connectmysqli::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=29");
$del = $db->deleteall ("Users", "ID in (27,28)");
$up = $db->update ("Users", $_post, "id=27");
Print_r ($list);

More interested in PHP related content readers can view the site topics: "PHP+MYSQLI Database Programming Skills Summary", "PHP object-oriented Program Design Introductory Course", "PHP Array" operation Skills Encyclopedia, "PHP Basic Grammar Introductory Course", " Summary of PHP operations and operator usage, "Summary of PHP Network programming skills", "PHP string (String) Usage Summary", "Php+mysql Database Operation Introduction" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design.

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.