PHP实现的通过参数生成MYSQL语句类完整实例,mysql语句
PHP实现的通过参数生成MYSQL语句类完整实例,mysql语句
本文实例讲述了PHP实现的通过参数生成MYSQL语句类。分享给大家供大家参考,具体如下:
这个类可以通过指定的表和字段参数创建SELECT ,INSERT , UPDATE 和 DELETE 语句。
这个类可以创建SQL语句的WHERE条件,像LIKE的查询语句,使用LEFT JOIN和ORDER 语句
<?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 " <b>Result Generate Insert</b><br> " ; $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 . " <br> " ;} echo " <b>Result Generate Update</b><br> " ; $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 . " <br> " ;} echo " <b>Result Generate Delete</b><br> " ; $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 . " <br> " ;} echo " <b>Result Generate List</b><br> " ; $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 . " <br> " ;} echo " <b>Result Generate List with search on all fields</b><br> " ; $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 . " <br> " ;} echo " <b>Result Generate List with search on some fields</b><br> " ; $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 . " <br> " ;} ?>
类代码:
<?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基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- PHP基于单例模式实现的mysql类
- php封装的连接Mysql类及用法分析
- 一个php Mysql类 可以参考学习熟悉下
- 十二个常见的PHP+MySql类免费CMS系统
- PHP实现基于mysqli的Model基类完整实例
- PHP使用Mysqli类库实现完美分页效果的方法
- PHP格式化MYSQL返回float类型的方法
- php实现Mysql简易操作类
- php简单操作mysql数据库的类

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











MySQL 데이터베이스에서 사용자와 데이터베이스 간의 관계는 권한과 테이블로 정의됩니다. 사용자는 데이터베이스에 액세스 할 수있는 사용자 이름과 비밀번호가 있습니다. 권한은 보조금 명령을 통해 부여되며 테이블은 Create Table 명령에 의해 생성됩니다. 사용자와 데이터베이스 간의 관계를 설정하려면 데이터베이스를 작성하고 사용자를 생성 한 다음 권한을 부여해야합니다.

데이터 통합 단순화 : AmazonRdsMysQL 및 Redshift의 Zero ETL 통합 효율적인 데이터 통합은 데이터 중심 구성의 핵심입니다. 전통적인 ETL (추출, 변환,로드) 프로세스는 특히 데이터베이스 (예 : AmazonRDSMySQL)를 데이터웨어 하우스 (예 : Redshift)와 통합 할 때 복잡하고 시간이 많이 걸립니다. 그러나 AWS는 이러한 상황을 완전히 변경 한 Zero ETL 통합 솔루션을 제공하여 RDSMYSQL에서 Redshift로 데이터 마이그레이션을위한 단순화 된 거의 실시간 솔루션을 제공합니다. 이 기사는 RDSMYSQL ZERL ETL 통합으로 Redshift와 함께 작동하여 데이터 엔지니어 및 개발자에게 제공하는 장점과 장점을 설명합니다.

MySQL 사용자 이름 및 비밀번호를 작성하려면 : 1. 사용자 이름과 비밀번호를 결정합니다. 2. 데이터베이스에 연결; 3. 사용자 이름과 비밀번호를 사용하여 쿼리 및 명령을 실행하십시오.

1. 올바른 색인을 사용하여 스캔 한 데이터의 양을 줄임으로써 데이터 검색 속도를 높이십시오. 테이블 열을 여러 번 찾으면 해당 열에 대한 인덱스를 만듭니다. 귀하 또는 귀하의 앱이 기준에 따라 여러 열에서 데이터가 필요한 경우 복합 인덱스 2를 만듭니다. 2. 선택을 피하십시오 * 필요한 열만 선택하면 모든 원치 않는 열을 선택하면 더 많은 서버 메모리를 선택하면 서버가 높은 부하 또는 주파수 시간으로 서버가 속도가 느려지며, 예를 들어 Creation_at 및 Updated_at 및 Timestamps와 같은 열이 포함되어 있지 않기 때문에 쿼리가 필요하지 않기 때문에 테이블은 선택을 피할 수 없습니다.

MySQL 데이터베이스 성능 최적화 안내서 리소스 집약적 응용 프로그램에서 MySQL 데이터베이스는 중요한 역할을 수행하며 대규모 트랜잭션 관리를 담당합니다. 그러나 응용 프로그램 규모가 확장됨에 따라 데이터베이스 성능 병목 현상은 종종 제약이됩니다. 이 기사는 일련의 효과적인 MySQL 성능 최적화 전략을 탐색하여 응용 프로그램이 고 부하에서 효율적이고 반응이 유지되도록합니다. 실제 사례를 결합하여 인덱싱, 쿼리 최적화, 데이터베이스 설계 및 캐싱과 같은 심층적 인 주요 기술을 설명합니다. 1. 데이터베이스 아키텍처 설계 및 최적화 된 데이터베이스 아키텍처는 MySQL 성능 최적화의 초석입니다. 몇 가지 핵심 원칙은 다음과 같습니다. 올바른 데이터 유형을 선택하고 요구 사항을 충족하는 가장 작은 데이터 유형을 선택하면 저장 공간을 절약 할 수있을뿐만 아니라 데이터 처리 속도를 향상시킬 수 있습니다.

MySQL에서 복사 및 붙여 넣기 단계는 다음 단계가 포함됩니다. 데이터를 선택하고 CTRL C (Windows) 또는 CMD C (MAC)로 복사; 대상 위치를 마우스 오른쪽 버튼으로 클릭하고 페이스트를 선택하거나 Ctrl V (Windows) 또는 CMD V (Mac)를 사용하십시오. 복사 된 데이터는 대상 위치에 삽입되거나 기존 데이터를 교체합니다 (데이터가 이미 대상 위치에 존재하는지 여부에 따라).

데이터베이스 산 속성에 대한 자세한 설명 산 속성은 데이터베이스 트랜잭션의 신뢰성과 일관성을 보장하기위한 일련의 규칙입니다. 데이터베이스 시스템이 트랜잭션을 처리하는 방법을 정의하고 시스템 충돌, 전원 중단 또는 여러 사용자의 동시 액세스가 발생할 경우에도 데이터 무결성 및 정확성을 보장합니다. 산 속성 개요 원자력 : 트랜잭션은 불가분의 단위로 간주됩니다. 모든 부분이 실패하고 전체 트랜잭션이 롤백되며 데이터베이스는 변경 사항을 유지하지 않습니다. 예를 들어, 은행 송금이 한 계정에서 공제되지만 다른 계정으로 인상되지 않은 경우 전체 작업이 취소됩니다. BeginTransaction; updateAccountssetBalance = Balance-100WH

다음 명령으로 MySQL 데이터베이스를보십시오. 서버에 연결하십시오. mysql -u username -p password run show database; 기존의 모든 데이터베이스를 가져 오려는 명령 데이터베이스 선택 : 데이터베이스 이름 사용; 보기 테이블 : 테이블 표시; 테이블 구조보기 : 테이블 이름을 설명합니다. 데이터보기 : 테이블 이름에서 *를 선택하십시오.
