Imitation hibernate database operation
<?php /** * @author:zhangmingshuang * @version:2011-10-13 * @param: */ function __autoload($class_name){ require(HIBERNATE_PATH.$class_name.".hbm.php"); } /** * 类似JAVA的HIBERNATE操作 * 注意点: * 1.模型层文件命名型为:tablename.hbm.php (如果要使用别的命名方式,则需要更改autoload方法里的文件名格式) * 2.模型层的class的名为:表名 (例:class tablename{.......}) * 3.模型层的字段需要与表的字段一致 * */ class hibernate{ private $table_name = ""; private $table_fileds = ""; private $fileds_value = ""; //private var $host; //地址localhost:3306 var $name; //用户名 var $pass; //密码 var $db; //数据库名 var $encode; //字符编码 ,utf8, 不是utf-8。or gbk //构造函数 function __construct($host, $name, $pass, $db, $encode='utf8'){ $this->host = $host; $this->name = $name; $this->pass = $pass; $this->db = $db; $this->encode = $encode; $this->connect(); } //连结数据库 function connect(){ $conn = mysql_connect($this->host, $this->name, $this->pass) or die("Could not connect : " . $this->error()); mysql_select_db($this->db) or die ("Could not select database : " . $this->error()); mysql_query("SET NAMES '$this->encode'"); //设置编码,防止中文乱码 } //析构函数 function __destruct(){ $this->close(); } /** * 保存数据 * @param $class_handle : 类句柄 */ function save($class_handle){ $this->set_table_filed($class_handle); $fileds = substr($this->table_fileds, strpos($this->table_fileds,",")+1,strlen($this->table_fileds)); $values = substr($this->fileds_value, strpos($this->fileds_value,",")+1,strlen($this->fileds_value)); $sql = "INSERT INTO `".$this->table_name."`(".$fileds.") VALUES(".$values.")"; $this->query($sql); } /** * 得取刚新增的ID */ function get_insert_id(){ return mysql_insert_id(); } /** * 获取数据 * @param $class_handle : 类句柄 * @param $val : 值 * @param $primary_key : 主建字段(默认为:模型层的第一个var) */ function get($class_handle,$primary_key_val,$primary_key=''){ $table_name = $this->get_table_name($class_handle);//取得表名 $filed_value_array = $this->get_filed_value($class_handle);//取得字段与值 if(empty($primary_key)){//如果主键未输入,则默认为模型层的第一个VAR //取得模型层的第一个VAR foreach ($filed_value_array as $key=>$value) { $primary_key = $key; break; } } $sql = "SELECT * FROM `".$table_name."` WHERE `".$primary_key."` = '".$primary_key_val."'"; $res = $this->query($sql); //mysql_fetch_array 为 mysql_fetch_row 扩展 可取出字段 $rows = mysql_fetch_array($res); if(!empty($rows)){ foreach($rows as $key=>$val){ if(is_numeric($key)){//删除 key 为数字的数据 unset($rows[$key]); } } $set_array = $this->get_class_set($class_handle);//取得字段 if(class_exists($table_name)){ $obj = new $table_name(); //将值SET进类中 foreach($rows as $key=>$val){ //取出取得的数据库数据的第一个记录(如:ID)匹配 foreach ($set_array as $k => $v){ if(strtolower($v)=='set'.$key){ $obj->$v($val); } } } return $obj; } }else{ return new $table_name(); } } /** * * 更新数据 * @param $class_handle : 类句柄 * @param $primary_key : 主建字段(默认为:模型层的第一个var) */ function update($class_handle,$primary_key=""){ $table_name = $this->get_table_name($class_handle);//取得表名 $filed_value_array = $this->get_filed_value($class_handle); if(empty($primary_key)){ //取得模型层的第一个VAR foreach ($filed_value_array as $key=>$value) { $primary_key = $key; break; } } foreach ($filed_value_array as $k=>$v){ if($k!=$primary_key){ $set_sql .= "`".$k."`='".$v."',"; } } $set_sql = rtrim($set_sql,",")."WHERE `".$primary_key."`='".$filed_value_array[$primary_key]."'"; $sql = "UPDATE `".$table_name."` SET ".$set_sql; $this->query($sql); } /** * 删除数据 * @param $class_handle : 类句柄 * @param $primary_key_val : 要删除的值 * @param $primary_key : 主建字段(默认为:模型层的第一个var) */ function delete($class_handle,$primary_key_val,$primary_key=''){ $table_name = $this->get_table_name($class_handle);//取得表名 $filed_value_array = $this->get_filed_value($class_handle); if(empty($primary_key)){ //取得模型层的第一个VAR foreach ($filed_value_array as $key=>$value) { $primary_key = $key; break; } } $sql = "DELETE FROM `".$table_name."` WHERE `".$primary_key."` = '".$primary_key_val."'"; if(is_array($primary_key_val)){ $primary_key_val = implode(",", $primary_key_val); $sql = "DELETE FROM `".$table_name."` WHERE `".$primary_key."`in(".$primary_key_val.")"; } $this->query($sql); } /** * 查找数据 * @param $class_handle */ function find($class_handle,$order="",$order_by="DESC"){ $table_name = $this->get_table_name($class_handle);//取得表名 $sql = "SELECT * FROM `".$table_name."` WHERE 1 = 1"; if(!empty($order)){ $sql .= " ORDER BY ".$order." ".$order_by; } return $this->query($sql); } /** * 根据条件查找数据 * @param $sql : SQL语句 * @param $filed_arr : 条件 */ //阻止sql注入 function p_filterXss($str){ $str = addslashes($str); $str = mysql_real_escape_string($str); return $str; } function query_by_sql($sql,$filed_arr){ //取出SQL语句中的?代替为字段 for($i=0;$i<count($filed_arr);$i++){ $filed_obj = mysql_real_escape_string(addslashes(trim($filed_arr[$i]))); if(strstr($sql,"?")){ $x_index = strpos($sql,"?");//找到第一个? //将语句分成二段 $sql = substr($sql, 0,$x_index)."'".$filed_arr[$i]."'".substr($sql, $x_index+1,strlen($sql)); } } return $this->query($sql); } /** * 分頁查詢 * @param $sql 查詢語句 * @param $page 當前頁 * @param $pageSize 每頁條數 */ function find_by_page($sql,$page,$page_size=10,$filed_arr=array()){ //取出SQL语句中的?代替为字段 for($i=0;$i<count($filed_arr);$i++){ $filed_obj = mysql_real_escape_string(addslashes(trim($filed_arr[$i]))); if(strstr($sql,"?")){ $x_index = strpos($sql,"?");//找到第一个? //将语句分成二段 $sql = substr($sql, 0,$x_index)."'".$filed_arr[$i]."'".substr($sql, $x_index+1,strlen($sql)); } } $page = empty($page) ? 1 : $page; return $this->query($sql." LIMIT " . ($page-1) * $page_size . ",$page_size"); } //返回记录集 function get_rows($result){ $rowNum = @mysql_num_rows($result); if ($rowNum > 0){ for ($i=0; $i<$rowNum; $i++){ $rows[$i] = mysql_fetch_array($result); } } return $rows; } //返回错误 function error(){ return mysql_error(); } //关闭 function close() { return @mysql_close(); } /** * mysql_query() 仅对 SELECT,SHOW,EXPLAIN 或 DESCRIBE 语句返回一个资源标识符,如果查询执行不正确则返回 FALSE。 * 对于其它类型的 SQL 语句,mysql_query() 在执行成功时返回 TRUE,出错时返回 FALSE。 * * @param string $sql * return TRUE/FALSE or 资源标识符 */ function query($sql){ $result = mysql_query($sql) or die("Query failed : " . $this->error()); return $result; } //統計記錄數 function count($result){ $rows_num = mysql_num_rows($result); return $rows_num; } /** * 将类名(表名)与类里的var(字段名)历遍取出 * @param $class_handle:类句柄 */ function set_table_filed($class_handle){ $this->table_name = get_class($class_handle); //取得表名 $object_vars = get_object_vars($class_handle);//取得字段与值 //将字段数组转成字符串 $filed_array = array();$value_array = array(); foreach ($object_vars as $key=>$val){ array_push($filed_array, '`'.$key.'`'); array_push($value_array, '\''.$val.'\''); } $this->table_fileds = implode(",", $filed_array); $this->fileds_value = implode(",", $value_array); } /** * 获取表名 * @param unknown_type $class_hanle */ function get_table_name($class_handle){ return get_class($class_handle); } /** * 取得类中的属性,生成SET的方法 * @param unknown_type $class_handle */ function get_class_set($class_handle){ $new_array = array(); $filed_array = get_object_vars($class_handle);//取得字段与值 foreach ($filed_array as $key=>$val){ array_push($new_array, "set".ucfirst($key)); } return $new_array; } /** * 取得类中的属性及对应值 * @param unknown_type $class_handle */ function get_filed_value($class_handle){ return get_object_vars($class_handle);//取得字段与值 } } #--------------------Example------------------------------- #要使用此方法需要配置HIBERNATE_PATH常量,指向:模型层的路径(model/) # model模层建立规则: #1.名字:类名.hbm.php #2.类名:table_name (class table_name{ }) #3.字段:即对表相对应的字段名(要与数据库一致) (var $id="";var $username="".....) #4.要配置GET AND SET 方法 #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #使用方法 #首先,需要实例化:hibernate对像即 #$hibernate = new hibernate(DB_HOST, DB_USER, DB_PASS, DB_NAME); #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #**调用保存 # $admin = new admin(); //不用配置inclue(require or include_once or require_once) #$admin->setUsername('admin'); #$admin->setNo('no'); #.... #$hibernate->save($admin); #**获取刚刚新增的数据ID #$id = $hibernate->get_insert_id(); #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #**根据ID获取数据 #$admin = new admin();//因为无法预知是否会事先初使化数据,所以,所有方法需要调进句柄 #$admin_get = $hibernate->get($admin,$id);//具体参数请自己查看 #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #**更新 #$admin = new admin(); #$admin_get = $hibernate->get($admin,$id); #$admin_get->setUsername('admin'); #$admin_get->setNo('no'); # $hibernate->update($admin_get);//更新的时候,不传ID 但是不能执行 $admin_get->setId(1),这样就更新别的数据了 #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #**删除 #$admin = new admin(); #$hibernate->delete(id);//ID可以为1或者数组 #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #**查找数据 # # ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
