before we've done the most hardcore part of ORM – piecing together strings, we need to execute the SQL statements that are pieced together. The insert operation is only completed here Toss (ii)-combine with PDO to implement a patchwork of SQL statements
we set up two tables first . User
| name |
type |
length |
decimal point |
allow null values |
| user_id |
Int |
11 |
0 |
False |
| User_name |
varchar |
20 |
0 |
False |
| User_pwd |
varchar |
32 |
0 |
False |
Order
| name |
type |
length |
decimal point |
allow null values |
| order_id |
Int |
11 |
0 |
False |
| user_id |
Int |
11 |
0 |
False |
| Order_price |
Decimal |
5 |
2 |
False |
effects After an insert is performed
The code following the PDO combination is as follows, as shown, interested can be studied under:
<?php ini_set (' display_errors ', 1);
Ini_set (' error_reporting ', e_all);
$map =function ($items) {if (!is_array ($items)) {return $items;
else {$result = "";
foreach ($items [1] as $item) {if ($result!= "") $result. = ",";
$result. = $item. $this->_aliastb ($item);//A similar news,news_class added to the form after the return $items [0]. $result;
}
}; Class Orm {public $sql =array (' Select ' => ' select ', ' From ' =>array (' from ', Array ()), ' whe Re "=>" where "," by "=>" Order By "," Insertinto "=>" insert into ",//insert operation" Insertf
Ields "=>", "values" => "values");
Public $errorCode = "";//error code public $sql _bak=[];
Public Function __construct () {$this->sql_bak= $this->sql; $this->db=new PDO ("Mysql:host=127.0.0.1;dbname=testorm", "root", "hello2016");//Initialize database connection} public function Sele
CT () {$fields =func_get_args (); foreach ($fields as $field) {if (Is_array ($field)) {$get _key=key ($field);//Gets the key of the array, which is actually the name of the table. , you also need to precede the field with the table prefix $this->__add (__function__, $this->_aliastb ($get _key).
$field [$get _key]);
else {$this->__add (__function__, $field);
} return $this;
//Insert Data Public Function Insert () {$params =func_get_args ();//Get variable parameters $fields =[];
$fields _values=[];
$callback =[];
foreach ($params as $param) {if (Is_array ($param)) {//Represents the field and value foreach ($param as $item) to be spliced {
Remove the field name $field =key ($item);
Remove the value of the field $field _value= $item [$field];
Insert the above field and field values into the corresponding array $fields []= $field; When the string is pieced together, determine if it is a string, and if it is a string, enclose the single quote if (is_string $field _vaLue)) {$field _value= "'". $field _value. "'";
$fields _values[]= $field _value;
After the parameters have been processed, construct the patchwork $this->__add ("Insertfields", "Implode ($fields, ', '),") to insert the field.
$this->__add ("Values", ' (' Implode ($fields _values, ', ') ');
///If the string description is the name of the table if (is_string ($param)) {$this->__add ("Insertinto", $param);
if (Is_bool ($param) && $param)//If the passed argument is a Boolean and true, the transaction is opened by default {
$this->db->begintransaction ();
} if (Is_callable ($param)) {$callback []= $param; } if (count ($callback) >0) {$this->exec ();//If there is an anonymous function, execute the SQL $this first-& Gt;clearconfig (); Restore configuration to the start state to prevent conflicts from executing other SQL.
You can save SQL to a class attribute, foreach ($callback as $call)//The last unified execution of each callback function {$call =closure::bind ($call, $this);//So you can use $this in anonymous functions, and this $this is an Orm object $call ();//Hand
Call anonymous function, this is callback}} return $this;
//Avoid SQL statements interfering with the function clearconfig ()//revert to the original configuration {$this->sql= $this->sql_bak;
}//Sort function order by ($STR, $order) {$order = '. $order;
if (Is_array ($STR)) {$TB =key ($STR); $this->__add (__function__, $this->_aliastb ($TB).
$str [$TB]. $order);
else {$this->__add (__function__, $str. $order);
return $this;
///Add alias Public function _aliastb to table ($tbName) {return ' _ '. $tbName; The public function from ($tableName)//processing from process {if (Is_array ($tableName)) {//is an array of words that represent multiple table associations if (Count ($tableName)!=2) return $this//parameter value is similar to [["Name" =>classid ""],["Name_class"]=> "id"], less than 2 to eliminate meaningful $TB 1=curre
NT ($tableName); $TB 2=next ($tAblename);
In the first step, the key value of the table is treated as a from parameter $tb 1_key=key ($TB 1);
$TB 1_value= $TB 1[$TB 1_key];
$TB 2_key=key ($TB 2);
$TB 2_value= $TB 2[$TB 2_key];
$this->__add (__function__, $TB 1_key);
$this->__add (__function__, $TB 2_key); The second step, piecing together where conditions $whereString = ' _ '. $TB 1_key. $TB 1_value. ' ='." _ ". $tb 2_key."
$TB 2_value;
$this->where ($whereString);
return $this;
The else {//string will represent a single table query $this->__add (__function__, $tableName);
return $this;
The public function where ($STR) {$this->__add (__function__, $str, "and");
return $this; The Public Function __add ($key, $str, $spliter = ",")//implements the additive of the string {//call does not exist method, directly returns if (!ARRAY_KEY_EX
Ists ($key, $this->sql)) return; if (Is_array ($this->sql[$key)) {//If the item already exists indicates that we do not do what to process if (!in_array $str,$this->sql[$key][1]) {$this->sql[$key][1][]= $str; } else {//if it is a string, direct string accumulation//if (Trim ($this->sql[$key])!= $key) if (preg_
Replace ('/\s/', ', $this->sql[$key])!= $key && preg_replace ("/\s/", ', $this->sql[$key])!= "")
$this->sql[$key].= $spliter;
$this->sql[$key].= $str;
The Public Function __tostring () {Global $map;
$map =closure::bind ($map, $this);
$filter =function ($value, $key) {//if (!is_string ($value)) return true;
if (Is_array ($value)) {if (count ($value [1]) >0) return true;
return false; //If an empty string does not participate in the additive if (Preg_replace ("/\s/", ", $value) = = $key | | preg_replace ("/\s/"," ", $value) = =
"") return false;
return true;
}; $this->sql=array_filter ($this->sql, $filter, Array_filter_use_both);
$res =array_map ($map, Array_values ($this->sql))//$this->sql= $this->sql_bak;
Return implode (Array_values ($res), ")//to reconstruct the new array into a string} public function exec () {//Test execution method $sql =strval ($this);
The _tostring method is automatically invoked $stmt = $this->db->prepare ($sql);
if (! $stmt->execute ())//Failed to execute, {if ($this->db->intransaction ())//To determine if transaction is turned on {
$this->db->rollback (),//rollback} $this->errorcode= $stmt->errorcode ();
echo executes SQL. $sql. ' Error, error code: '. $this->errorcode. ', error message: ". $stmt->errorinfo () [2];
return $this;
function Getlastinsertid ()//Get previous SQL execution {return $this->db->lastinsertid ();
The function getAll ()//Gets the result of all removal {return $this->db->fetchall (); function commit () {//COMMIT transaction if ($this->db-> Intransaction ()) $this->db->commit ();
}} $orm =new orm (); echo $orm->insert (true,[[' user_name ' => "seven"], [' User_pwd ' =>md5 (' 123 ')]], "User", function () {$userid = $this->getlastinsertid ();//Get the user ID $this->insert after registration ([[' User_ID ' =>intval
($userid)], [' Order_price ' =>100],], ' orders ', function () {if ($this->errorcode== "")
{$this->commit ();
echo "sucess!";
else {echo "fail!";
}
});
});