PHP-based ORM Operation MySQL Database

Source: Internet
Author: User
ORM----oriented relationship Mapper, which is to manipulate the database in an object-oriented manner. In the final analysis, the encapsulation of SQL statements is still the case. In this paper, we mainly introduce PHP based on ORM Operation MySQL database, combined with specific examples of PHP for MySQL database common operation of the encapsulation and use of skills, hope to be useful to everyone.

First, our database has the following table:

We want to be able to use Setuserid ("11111") on this table, that is, you can set Userid;getuserid () to obtain both the UserID of the object. So, we need to create a model object that corresponds to a table in the database.

Since the model for each table should have a set/get operation, we define it with a parent class Basicmodel. All other model is inherited to this model.

The code for Basicmodel is as follows:


<?php */   * author:tammy Pi   * Function:model class base class, encapsulated Set/get operation   */  class basicmodel{    Private $map = null;    function Tbuser () {      $this->map = Array ();    }    function __set ($key, $value) {      $this->map[$key] = $value;    }    function __get ($key) {      return $this->map[$key];    }    function __call ($name, $arguments) {      if (substr ($name, 0,3) = = ' Set ') {$this->__set (Strtolower (substr (        $ name,3)), $arguments [0]);      } else{        return $this->__get (Strtolower (substr ($name, 3));}}}  ? >

Then, the model class Tbuser that corresponds to the Tb_user table inherits it.


<?php  require_once ("basicmodel.php");  Class Tbuser extends basicmodel{  }?>

In this way, we can perform set/get operations on the Tbuser instance.

To operate the database with ORM, you must be able to findbywhere ($where) The query, return an array of objects, save ($tbUser), delete ($obj), and update ($obj).

Essentially, the user is passing in an object, and we then use the code to convert the object to an SQL statement. In essence, SQL statements are executed.

So, we represent a series of operations with interfaces. The code for Ibasicdao is as follows:


<?php  interface Ibasicdao {public    function findbywhere ($where);    Public Function Findwhereorderby ($where, $order, $start =null, $limit =null);    Public function Save ($obj);    Public Function Delete ($obj);    Public Function Update ($obj);  }? >

The most important thing is to implement this interface. Completes the conversion of objects and SQL.
The code for Basicdao is as follows:


<?php require_once ("ibasicdao.php");    Class Basicdao implements ibasicdao{protected $modelName = null;    Private $tableName = null;    Private $h = "localhost";    Private $user = "root";    Private $pass = "root";    Private $db = "Db_toilet"; Get connection Public Function getconnection () {$conn = Mysqli_connect ($this->h, $this->user, $this->pass, $this-&gt      ;d b);    return $conn; }//Initialize public function init () {//To get the name of the table according to the model $this->tablename = Strtolower (substr ($this->mode lname,0,2)). "    _ ". Strtolower (substr ($this->modelname,2));      }//Gets the column name of a table public function GetColumn ($tableName) {$sql = "show columns from". $tableName;      $conn = $this->getconnection ();      $columns = Array ();        if ($conn!=null) {$rtn = Mysqli_query ($conn, $sql);        while ($rtn!==false&& ($row =mysqli_fetch_array ($RTN))!=null) {$columns [] = $row [0];      } mysqli_close ($conn);    } return $columns;  }  Conditional query Public Function Findbywhere ($where) {//Gets the column name of the data table $columns = $this->getcolumn ($this->tablename);      Splicing the SQL statement $sql = "SELECT * from". $this->tablename. "where". $where;      $conn = $this->getconnection ();      $arr = Array ();        if ($conn!=null) {$rtn = Mysqli_query ($conn, $sql);          while ($rtn!==false&& ($row =mysqli_fetch_array ($RTN))!=null) {$index =-1;          $obj = new $this->modelname ();          foreach ($columns as $column) {$obj->{"set". Ucfirst ($column)} ($row [+ + $index]);        } $arr [] = $obj;      } mysqli_close ($conn);    } return $arr;  }//paged query; Support sort public Function Findwhereorderby ($where, $order, $start =null, $limit =null) {//Get the column name of the data table $columns      = $this->getcolumn ($this->tablename);      Splicing the SQL statement $sql = "SELECT * from". $this->tablename. "where". $where. "ORDER by". $order; if ($start!=null&& $limit!=null) {$sql. = "LImit ". $start.", ". $limit;      } $conn = $this->getconnection ();      $arr = Array ();        if ($conn!=null) {$rtn = Mysqli_query ($conn, $sql);          while ($rtn!==false&& ($row =mysqli_fetch_array ($RTN))!=null) {$index =-1;          $obj = new $this->modelname ();          foreach ($columns as $column) {$obj->{"set". Ucfirst ($column)} ($row [+ + $index]);        } $arr [] = $obj;      } mysqli_close ($conn);    } return $arr;      }//Save operation Public Function Save ($obj) {$columns = $this->getcolumn ($this->tablename);      $conn = $this->getconnection ();      $tag = false; if ($conn!=null) {$sql = "insert into". $this->tablename. "        (";        foreach ($columns as $column) {$sql. = $column. ","; } $sql = substr ($sql, 0,strlen ($sql)-1). ")        Values (";          foreach ($columns as $column) {$value = $obj->{"Get". Ucfirst ($column)} (); Determine the type of $value if ($value ==null) {$sql. = "null,";          }else if (Preg_match ("/^[0-9]*$/", $value)) {//is a digital $sql. = $value. ",";          }else{$sql. = "'". $value. "',";        }} $sql = substr ($sql, 0,strlen ($sql)-1);        $sql. = ")";        Execute SQL statement mysqli_query ($conn, $sql);        $tag = true;      Mysqli_close ($conn);    } return $tag;      }//delete operation public Function Delete ($obj) {$conn = $this->getconnection ();      $tag = false;        if ($conn!=null) {$sql = "delete from". $this->tablename. "Where";        $columns = $this->getcolumn ($this->tablename);        $value = $obj->{"Get". Ucfirst ($columns [0])} (); if ($value!=null) {//is the number if (Preg_match ("/^[0-9]*$/", $value)) {$sql. = $columns [0]. "          = ". $value; }else{$sql. = $columns [0]. "          = ' ". $value." ' ";          }//Execute Mysqli_query ($conn, $sql);        $tag = true; } MySQLI_close ($conn);    } return $tag;      }//Update operation public Function Update ($obj) {$conn = $this->getconnection ();      $columns = $this->getcolumn ($this->tablename);      $tag = false;        if ($conn!=null) {$sql = "update". $this->tablename. "Set";          for ($i =1; $i <count ($columns); $i + +) {$column = $columns [$i];          $value = $obj->{"Get". Ucfirst ($columns [$i])} (); if ($value ==null) {$sql. = $column. "          =null, "; }else if (Preg_match ("/^[0-9]*$/", $value)) {$sql. = $column. "          = ". $value.", "; }else{$sql. = $column. "          = ' ". $value." ', ";        }} $sql = substr ($sql, 0,strlen ($sql)-1);        $sql. = "where";        $tempColumn = $columns [0];        $tempValue = $obj->{"Get". Ucfirst ($columns [0])} (); if (Preg_match ("/^[0-9]*$/", $tempValue)) {$sql. = $tempColumn. "        = ". $tempValue; }else{$sql. = $tempColumn. "        = ' ". $tempValue." ' "; }        //Perform Operation Mysqli_query ($conn, $sql);        $tag = true;      Mysqli_close ($conn);    } return $tag; }}?>

Then, the Tb_user table operation, the main use is Tbuserdao, it will modelname set to "Tbuser", the code will know that the operation of the table is Tb_user, and then you can do a series of operations.


<?php  require_once ("basicdao.php");  Require_once (".. /model/tbuser.php ");  Class Tbuserdao extends basicdao{    function Tbuserdao () {      $this->modelname = ' tbuser ';      Parent::init ();    }  }? >

Then, you can manipulate the database in an object-oriented manner.
Such as:


$tbUserDAO = new Tbuserdao (), $tbUser = new Tbuser (); $tbUser->setuserid ("fetchingsoft@163.com"); $tbUser Setusername ("fetching"); $tbUserDAO->update ($tbUser); echo "executed successfully!" ";p Rint_r ($list);

This updates the records in the database.

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.