当前位置: 首页 > 编程文章 >

PHP通过参数生成MySQL语句类完整实例

PHP通过参数生成MySQL语句类完整实例

作者:林辰时间:2026-01-25 12:33:26浏览:964

本文介绍了一个PHP实现的类,该类能够根据指定的表和字段参数自动生成SELECT、INSERT、UPDATE和DELETE等SQL语句。此外,它还支持构建WHERE条件(如LIKE查询)、LEFT JOIN以及ORDER排序功能。通过提供完整的类代码示例,帮助开发者快速掌握在PHP中动态构造复杂SQL查询的方法。

本文目录展开

PHP生成MySQL语句类介绍

本示例详细解析了利用PHP编写的用于生成MySQL语句的工具类。以下内容旨在为读者提供参考与借鉴。

该工具类允许用户传入特定的数据表名称及字段信息,进而自动组装出SELECT、INSERT、UPDATE以及DELETE类型的SQL指令。

除了基础语句生成外,此类还具备构建WHERE过滤条件的能力,例如支持模糊匹配的LIKE操作,同时也能处理LEFT JOIN连接查询及ORDER BY排序逻辑。


<?php
/* *******************************************************************
Example file
This example shows how to use the MyLibSQLGen class
The example is based on the following MySQL table:
CREATE TABLE customer (
id int(10) unsigned NOT NULL auto_increment,
name varchar(60) NOT NULL default '',
address varchar(60) NOT NULL default '',
city varchar(60) NOT NULL default '',
PRIMARY KEY (cust_id)
) TYPE=MyISAM;
******************************************************************* */
require_once ( " class_mylib_SQLGen-1.0.php " );
$fields = Array ( " name " , " address " , " city " );
$values = Array ( " Fadjar " , " Resultmang Raya Street " , " Jakarta " );
$tables = Array ( " customer " );
echo  " Result Generate Insert
" ;
$object = new MyLibSQLGen();
$object -> clear_all_assign(); // to refresh all property but it no need when first time execute
$object -> setFields( $fields );
$object -> setValues( $values );
$object -> setTables( $tables );
if ( ! $object -> getInsertSQL()){ echo  $object -> Error; exit ;}
else { $sql = $object -> Result; echo  $sql . "
    " ;}
    echo  " Result Generate Update
    " ;
    $fields = Array ( " name " , " address " , " city " );
    $values = Array ( " Fadjar " , " Resultmang Raya Street " , " Jakarta " );
    $tables = Array ( " customer " );
    $id = 1 ;
    $conditions [ 0 ][ " condition " ] = " id='$id' " ;
    $conditions [ 0 ][ " connection " ] = "" ;
    $object -> clear_all_assign();
    $object -> setFields( $fields );
    $object -> setValues( $values );
    $object -> setTables( $tables );
    $object -> setConditions( $conditions );
    if ( ! $object -> getUpdateSQL()){ echo  $object -> Error; exit ;}
    else { $sql = $object -> Result; echo  $sql . "
        " ;}
        echo  " Result Generate Delete
        " ;
        $tables = Array ( " customer " );
        $conditions [ 0 ][ " condition " ] = " id='1' " ;
        $conditions [ 0 ][ " connection " ] = " OR " ;
        $conditions [ 1 ][ " condition " ] = " id='2' " ;
        $conditions [ 1 ][ " connection " ] = " OR " ;
        $conditions [ 2 ][ " condition " ] = " id='4' " ;
        $conditions [ 2 ][ " connection " ] = "" ;
        $object -> clear_all_assign();
        $object -> setTables( $tables );
        $object -> setConditions( $conditions );
        if ( ! $object -> getDeleteSQL()){ echo  $object -> Error; exit ;}
        else { $sql = $object -> Result; echo  $sql . "
            " ;}
            echo  " Result Generate List
            " ;
            $fields = Array ( " id " , " name " , " address " , " city " );
            $tables = Array ( " customer " );
            $id = 1 ;
            $conditions [ 0 ][ " condition " ] = " id='$id' " ;
            $conditions [ 0 ][ " connection " ] = "" ;
            $object -> clear_all_assign();
            $object -> setFields( $fields );
            $object -> setTables( $tables );
            $object -> setConditions( $conditions );
            if ( ! $object -> getQuerySQL()){ echo  $object -> Error; exit ;}
            else { $sql = $object -> Result; echo  $sql . "
                " ;}
                echo  " Result Generate List with search on all fields
                " ;
                $fields = Array ( " id " , " name " , " address " , " city " );
                $tables = Array ( " customer " );
                $id = 1 ;
                $search = " Fadjar Nurswanto " ;
                $object -> clear_all_assign();
                $object -> setFields( $fields );
                $object -> setTables( $tables );
                $object -> setSearch( $search );
                if ( ! $object -> getQuerySQL()){ echo  $object -> Error; exit ;}
                else { $sql = $object -> Result; echo  $sql . "
                    " ;}
                    echo  " Result Generate List with search on some fields
                    " ;
                    $fields = Array ( " id " , " name " , " address " , " city " );
                    $tables = Array ( " customer " );
                    $id = 1 ;
                    $search = Array (
                    " name " => " Fadjar Nurswanto " ,
                    " address " => " Tomang Raya "
                    );
                    $object -> clear_all_assign();
                    $object -> setFields( $fields );
                    $object -> setTables( $tables );
                    $object -> setSearch( $search );
                    if ( ! $object -> getQuerySQL()){ echo  $object -> Error; exit ;}
                    else { $sql = $object -> Result; echo  $sql . "
                        " ;}
                        ?>

以下是该类的具体源代码实现:


<?php
 /* 
Created By    : Fadjar Nurswanto <fajr_n@rindudendam.net>
DATE      : 2006-08-02
PRODUCTNAME    : class MyLibSQLGen
PRODUCTVERSION  : 1.0.0
DESCRIPTION    : class yang berfungsi untuk menggenerate SQL
DENPENCIES    :
 */ 
 class MyLibSQLGen
{
   var  $Result ;
   var  $Tables = Array ();
   var  $Values = Array ();
   var  $Fields = Array ();
   var  $Conditions = Array ();
   var  $Condition ;
   var  $LeftJoin = Array ();
   var  $Search ;
   var  $Sort = " ASC " ;
   var  $Order ;
   var  $Error ;
   function MyLibSQLGen(){}
   function BuildCondition()
  {
     $funct = " BuildCondition " ;
     $className = get_class ( $this );
     $conditions = $this -> getConditions();
     if ( ! $conditions ){ $this -> dbgDone( $funct ); return  true ;}
     if ( ! is_array ( $conditions ))
    {
       $this -> Error = " $className::$funct Variable conditions not Array " ;
       return ;
    }
     for ( $i = 0 ; $i < count ( $conditions ); $i ++ )
    {
       $this -> Condition .= $conditions [ $i ][ " condition " ] . "  " . $conditions [ $i ][ " connection " ] . "  " ;
    }
     return  true ;
  }
   function BuildLeftJoin()
  {
     $funct = " BuildLeftJoin " ;
     $className = get_class ( $this );
     if ( ! $this -> getLeftJoin()){ $this -> Error = " $className::$funct Property LeftJoin was empty " ; return ;}
     $LeftJoinVars = $this -> getLeftJoin();
     $hasil = false ;
     foreach ( $LeftJoinVars  as  $LeftJoinVar )
    {
      @ $hasil .= " LEFT JOIN " . $LeftJoinVar [ " table " ];
       foreach ( $LeftJoinVar [ " on " ] as  $var )
      {
        @ $condvar .= $var [ " condition " ] . "  " . $var [ " connection " ] . "  " ;
      }
       $hasil .= " ON ( " . $condvar . " ) " ;
       unset ( $condvar );
    }
     $this -> ResultLeftJoin = $hasil ;
     return  true ;
  }
   function BuildOrder()
  {
     $funct = " BuildOrder " ;
     $className = get_class ( $this );
     if ( ! $this -> getOrder()){ $this -> Error = " $className::$funct Property Order was empty " ; return ;}
     if ( ! $this -> getFields()){ $this -> Error = " $className::$funct Property Fields was empty " ; return ;}
     $Fields = $this -> getFields();
     $Orders = $this -> getOrder();
     if ( ereg ( " , " , $Orders )){ $Orders = explode ( " , " , $Order );}
     if ( ! is_array ( $Orders )){ $Orders = Array ( $Orders );}
     foreach ( $Orders  as  $Order )
    {
       if ( ! is_numeric ( $Order )){ $this -> Error = " $className::$funct Property Order not Numeric " ; return ;}
       if ( $Order  >  count ( $this -> Fields)){ $this -> Error = " $className::$funct Max value of property Sort is " . count ( $this -> Fields); return ;}
      @ $xorder .= $Fields [ $Order ] . " , " ;
    }
     $this -> ResultOrder = " ORDER BY " . substr ( $xorder , 0 ,- 1 );
     return  true ;
  }
   function BuildSearch()
  {
     $funct = " BuildSearch " ;
     $className = get_class ( $this );
     if ( ! $this -> getSearch()){ $this -> Error = " $className::$funct Property Search was empty " ; return ;}
     if ( ! $this -> getFields()){ $this -> Error = " $className::$funct Property Fields was empty " ; return ;}
     $Fields = $this -> getFields();
     $xvalue = $this -> getSearch();
     if ( is_array ( $xvalue ))
    {
       foreach ( $Fields  as  $field )
      {
         if (@ $xvalue [ $field ])
        {
           $Values = explode ( "  " , $xvalue [ $field ]);
           foreach ( $Values  as  $Value )
          {
            @ $hasil .= $field . " LIKE '% " . $Value . " %' OR " ;
          }
           if ( $hasil )
          {
            @ $hasil_final .= " ( " . substr ( $hasil , 0 ,- 4 ) . " ) AND " ;
             unset ( $hasil );
          }
        }
      }
       $hasil = $hasil_final ;
    }
     else 
    {
       foreach ( $Fields  as  $field )
      {
         $Values = explode ( "  " , $xvalue );
         foreach ( $Values  as  $Value )
        {
          @ $hasil .= $field . " LIKE '% " . $Value . " %' OR " ;
        }
      }
    }
     $this -> ResultSearch = substr ( $hasil , 0 ,- 4 );
     return  true ;
  }
   function clear_all_assign()
  {
     $this -> Result = null ;
     $this -> ResultSearch = null ;
     $this -> ResultLeftJoin = null ;
     $this -> Result = null ;
     $this -> Tables = Array ();
     $this -> Values = Array ();
     $this -> Fields = Array ();
     $this -> Conditions = Array ();
     $this -> Condition = null ;
     $this -> LeftJoin = Array ();
     $this -> Sort = " ASC " ;
     $this -> Order = null ;
     $this -> Search = null ;
     $this -> fieldSQL = null ;
     $this -> valueSQL = null ;
     $this -> partSQL = null ;
     $this -> Error = null ;
     return  true ;
  }
   function CombineFieldValue( $manual = false )
  {
     $funct = " CombineFieldsPostVar " ;
     $className = get_class ( $this );
     $fields = $this -> getFields();
     $values = $this -> getValues();
     if ( ! is_array ( $fields ))
    {
       $this -> Error = " $className::$funct Variable fields not Array " ;
       return ;
    }
     if ( ! is_array ( $values ))
    {
       $this -> Error = " $className::$funct Variable values not Array " ;
       return ;
    }
     if ( count ( $fields ) != count ( $values ))
    {
       $this -> Error = " $className::$funct Count of fields and values not match " ;
       return ;
    }
     for ( $i = 0 ; $i < count ( $fields ); $i ++ )
    {
      @ $this -> fieldSQL .= $fields [ $i ] . " , " ;
       if ( $fields [ $i ] ==  " pwd "  ||  $fields [ $i ] ==  " password "  ||  $fields [ $i ] ==  " pwd " )
      {
        @ $this -> valueSQL .= " password(' " . $values [ $i ] . " '), " ;
        @ $this -> partSQL .= $fields [ $i ] . " =password(' " . $values [ $i ] . " '), " ;
      }
       else 
      {
         if ( is_numeric ( $values [ $i ]))
        {
          @ $this -> valueSQL .= $values [ $i ] . " , " ;
          @ $this -> partSQL .= $fields [ $i ] . " = " . $values [ $i ] . " , " ;
        }
         else 
        {
          @ $this -> valueSQL .= " ' " . $values [ $i ] . " ', " ;
          @ $this -> partSQL .= $fields [ $i ] . " =' " . $values [ $i ] . " ', " ;
        }
      }
    }
     $this -> fieldSQL = substr ( $this -> fieldSQL , 0 ,- 1 );
     $this -> valueSQL = substr ( $this -> valueSQL , 0 ,- 1 );
     $this -> partSQL = substr ( $this -> partSQL , 0 ,- 1 );
     return  true ;
  }
   function getDeleteSQL()
  {
     $funct = " getDeleteSQL " ;
     $className = get_class ( $this );
     $Tables = $this -> getTables();
     if ( ! $Tables  ||  ! count ( $Tables ))
    {
       $this -> dbgFailed( $funct );
       $this -> Error = " $className::$funct Table was empty " ;
       return ;
    }
     for ( $i = 0 ; $i < count ( $Tables ); $i ++ )
    {
      @ $Table .= $Tables [ $i ] . " , " ;
    }
     $Table = substr ( $Table , 0 ,- 1 );
     $sql = " DELETE FROM " . $Table ;
     if ( $this -> getConditions())
    {
       if ( ! $this -> BuildCondition()){ $this -> dbgFailed( $funct ); return ;}
       $sql .= " WHERE " . $this -> getCondition();
    }
     $this -> Result = $sql ;
     return  true ;
  }
   function getInsertSQL()
  {
     $funct = " getInsertSQL " ;
     $className = get_class ( $this );
     if ( ! $this -> getValues()){ $this -> Error = " $className::$funct Property Values was empty " ; return ;}
     if ( ! $this -> getFields()){ $this -> Error = " $className::$funct Property Fields was empty " ; return ;}
     if ( ! $this -> getTables()){ $this -> Error = " $className::$funct Property Tables was empty " ; return ;}
     if ( ! $this -> CombineFieldValue()){ $this -> dbgFailed( $funct ); return ;}
     $Tables = $this -> getTables();
     $sql = " INSERT INTO " . $Tables [ 0 ] . " ( " . $this -> fieldSQL . " ) VALUES ( " . $this -> valueSQL . " ) " ;
     $this -> Result = $sql ;
     return  true ;
  }
   function getUpdateSQL()
  {
     $funct = " getUpdateSQL " ;
     $className = get_class ( $this );
     if ( ! $this -> getValues()){ $this -> Error = " $className::$funct Property Values was empty " ; return ;}
     if ( ! $this -> getFields()){ $this -> Error = " $className::$funct Property Fields was empty " ; return ;}
     if ( ! $this -> getTables()){ $this -> Error = " $className::$funct Property Tables was empty " ; return ;}
     if ( ! $this -> CombineFieldValue()){ $this -> dbgFailed( $funct ); return ;}
     if ( ! $this -> BuildCondition()){ $this -> dbgFailed( $funct ); return ;}
     $Tables = $this -> getTables();
     $sql = " UPDATE " . $Tables [ 0 ] . " SET " . $this -> partSQL . " WHERE " . $this -> getCondition();
     $this -> Result = $sql ;
     return  true ;
  }
   function getQuerySQL()
  {
     $funct = " getQuerySQL " ;
     $className = get_class ( $this );
     if ( ! $this -> getFields()){ $this -> Error = " $className::$funct Property Fields was empty " ; return ;}
     if ( ! $this -> getTables()){ $this -> Error = " $className::$funct Property Tables was empty " ; return ;}
     $Fields = $this -> getFields();
     $Tables = $this -> getTables();
     foreach ( $Fields  as  $Field ){@ $sql_raw .= $Field . " , " ;}
     foreach ( $Tables  as  $Table ){@ $sql_table .= $Table . " , " ;}
     $this -> Result = " SELECT " . substr ( $sql_raw , 0 ,- 1 ) . " FROM " . substr ( $sql_table , 0 ,- 1 );
     if ( $this -> getLeftJoin())
    {
       if ( ! $this -> BuildLeftJoins()){ $this -> dbgFailed( $funct ); return ;}
       $this -> Result .= "  " . $this -> ResultLeftJoin;
    }
     if ( $this -> getConditions())
    {
       if ( ! $this -> BuildCondition()){ $this -> dbgFailed( $funct ); return ;}
       $this -> Result .= " WHERE ( " . $this -> Condition . " ) " ;
    }
     if ( $this -> getSearch())
    {
       if ( ! $this -> BuildSearch()){ $this -> dbgFailed( $funct ); return ;}
       if ( $this -> ResultSearch)
      {
         if ( eregi ( " WHERE " , $this -> Result)){ $this -> Result .= " AND " . $this -> ResultSearch;}
         else { $this -> Result .= " WHERE " . $this -> ResultSearch;}
      }
    }
     if ( $this -> getOrder())
    {
       if ( ! $this -> BuildOrder()){ $this -> dbgFailed( $funct ); return ;}
       $this -> Result .= "  " . $this -> ResultOrder;
    }
     if ( $this -> getSort())
    {
       if (@ $this -> ResultOrder)
      {
         $this -> Result .= "  " . $this -> getSort();
      }
    }
     return  true ;
  }
   function getCondition(){ return @ $this -> Condition;}
   function getConditions(){ if ( count (@ $this -> Conditions) &&  is_array (@ $this -> Conditions)){ return @ $this -> Conditions;}}
   function getFields(){ if ( count (@ $this -> Fields) &&  is_array (@ $this -> Fields)){ return @ $this -> Fields;}}
   function getLeftJoin(){ if ( count (@ $this -> LeftJoin) &&  is_array (@ $this -> LeftJoin)){ return @ $this -> LeftJoin;}}
   function getOrder(){ return @ $this -> Order;}
   function getSearch(){ return @ $this -> Search;}
   function getSort(){ return @ $this -> Sort ;}
   function getTables(){ if ( count (@ $this -> Tables) &&  is_array (@ $this -> Tables)){ return @ $this -> Tables;}}
   function getValues(){ if ( count (@ $this -> Values) &&  is_array (@ $this -> Values)){ return @ $this -> Values;}}
   function setCondition( $input ){ $this -> Condition = $input ;}
   function setConditions( $input )
  {
     if ( is_array ( $input )){ $this -> Conditions = $input ;}
     else { $this -> Error = get_class ( $this ) . " ::setConditions Parameter input not array " ; return ;}
  }
   function setFields( $input )
  {
     if ( is_array ( $input )){ $this -> Fields = $input ;}
     else { $this -> Error = get_class ( $this ) . " ::setFields Parameter input not array " ; return ;}
  }
   function setLeftJoin( $input )
  {
     if ( is_array ( $input )){ $this -> LeftJoin = $input ;}
     else { $this -> Error = get_class ( $this ) . " ::setFields Parameter input not array " ; return ;}
  }
   function setOrder( $input ){ $this -> Order = $input ;}
   function setSearch( $input ){ $this -> Search = $input ;}
   function setSort( $input ){ $this -> Sort = $input ;}
   function setTables( $input )
  {
     if ( is_array ( $input )){ $this -> Tables = $input ;}
     else { $this -> Error = get_class ( $this ) . " ::setTables Parameter input not array " ; return ;}
  }
   function setValues( $input )
  {
     if ( is_array ( $input )){ $this -> Values = $input ;}
     else { $this -> Error = get_class ( $this ) . " ::setValues Parameter input not array " ; return ;}
  }
}
?>

期待上述内容能为各位PHP开发者的编程工作带来便利。

上一篇
PHP模板引擎Smarty保留变量详解

Smarty模板引擎提供无需分配即可直接使用的保留变量。通过$smarty对象可访问页面请求参数(如get、post)、PHP定义的常量及系统环境变量,并支持读取配置文件内容。此外,还能获取服务器当前时间戳、内建函数capture捕获的数据以及foreach循环的迭代信息,极大简化了模板中的逻辑处理。

下一篇
非集成环境PHP运行环境搭建:Apache与MySQL配置详解

本文介绍在非集成环境下手动搭建PHP运行环境的步骤,涵盖Apache安装路径选择、通过httpd.conf加载PHP模块、php.ini时区及数据库扩展配置,以及MySQL数据库的安装与连接验证。

相关文章

更多
PHP操作MySQL数据库:从工具选择到实战案例

本文介绍了使用PHP操作MySQL数据库的完整流程,涵盖命令行、Navicat及phpMyAdmin等常用管理工具。重点讲解HTTP GET与POST方式在表单数据传递中的区别与安全特性。通过mysqli扩展的基础步骤(创建连接、选择库、设置编码、执行SQL、关闭连接),演示了增删改查的具体实现,并对比了fetch_assoc、fetch_row和fetch_array三种结果集获取方法的差异。最后结合注册与登录两个实际案例,展示如何将前端用户输入安全地存入数据库并进行验证。

2026.01.07 1,004
PHP实现MySQL数据库自动备份的方法与代码

本文介绍利用PHP函数实现MySQL数据库自动备份的具体方法。通过fopen、fwrite等文件操作函数结合PDO查询,获取表结构和数据并生成标准SQL文件。该方法无需依赖mysqldump命令行工具,适合在Web环境中集成使用,确保数据安全。

2025.04.24 999
PHP连接及读写MySQL数据库的常用代码示例

本文总结了使用PHP连接MySQL数据库以及进行数据读取和写入的常用方法。通过将服务器、用户名、密码等配置信息定义为变量并封装在独立文件中,便于复用。核心步骤包括建立数据库连接、设置字符编码、选择目标数据库,随后利用mysql_query执行SQL语句,并通过循环结构遍历结果集以读取数据,或构造INSERT语句完成数据写入操作。

2026.05.01 992
基于Docker搭建PHP+Nginx+Swoole+MySQL+Redis开发环境

本文介绍在CentOS 7.4环境下,使用Docker和Docker Compose快速搭建包含Nginx、PHP-FPM(含Swoole、Redis、PDO_MySQL扩展)、MySQL和Redis的完整Web开发环境。通过自定义镜像构建、容器编排及配置文件调整,实现各服务间的通信与功能验证。

2026.10.23 985
PHP操作MySQL datetime字段:插入、查询与时间提取方法

在PHP中处理MySQL的datetime类型时,需遵循YYYY-MM-DD HH:MI:SS格式。本文演示了如何通过PHP创建包含datetime字段的表,并正确插入日期数据。针对2026-01-28等特定日期的查询,直接使用DATE()函数可避免时间部分导致的匹配错误。此外,介绍了利用HOUR、MINUTE等内置函数从datetime值中提取年、月、日等具体时间组件的方法。

2025.09.11 984
PHP脚本自动清理MySQL长时间Sleep死连接

当MySQL数据库中积累过多处于Sleep状态且持续时间较长的连接时,会耗尽可用连接数导致其他用户无法连接。通过编写PHP脚本结合系统计划任务,可每两分钟自动检测并终止超过120秒的Sleep进程,从而有效防止数据库服务器因连接数满负荷而瘫痪。

2025.01.13 973

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。