search
HomeBackend DevelopmentPHP TutorialImitation 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=&#39;utf8&#39;){
$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 &#39;$this->encode&#39;"); //设置编码,防止中文乱码
}
//析构函数
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=&#39;&#39;){
   
    $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."` = &#39;".$primary_key_val."&#39;";
    $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)==&#39;set&#39;.$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."`=&#39;".$v."&#39;,";
}
}
$set_sql = rtrim($set_sql,",")."WHERE `".$primary_key."`=&#39;".$filed_value_array[$primary_key]."&#39;";
$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=&#39;&#39;){
    $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."` = &#39;".$primary_key_val."&#39;";
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)."&#39;".$filed_arr[$i]."&#39;".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)."&#39;".$filed_arr[$i]."&#39;".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, &#39;`&#39;.$key.&#39;`&#39;);
array_push($value_array, &#39;\&#39;&#39;.$val.&#39;\&#39;&#39;);
}
$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(&#39;admin&#39;);
#$admin->setNo(&#39;no&#39;);
#....
#$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(&#39;admin&#39;);
#$admin_get->setNo(&#39;no&#39;);
#  $hibernate->update($admin_get);//更新的时候,不传ID 但是不能执行 $admin_get->setId(1),这样就更新别的数据了
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#**删除
#$admin = new admin();
#$hibernate->delete(id);//ID可以为1或者数组
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#**查找数据
#
#
?>

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.