데이터베이스 연결을 매우 쉽게 처리할 수 있는 클래스입니다. 범용 상호 교환 가능한 CRUD 시스템입니다.
이것은 버전 4 의 사용자를 중단시키는 버전 5 입니다.
주로:
global
함수 ezFunctions.php 파일에서 namespace
를 사용합니다. 전역 함수를 사용하려면 사용자가 다음과 같은 .php
파일을 시작해야 합니다.
use function ezsql functions where ;
// Or
use function ezsql functions {
getInstance ,
selecting ,
inserting ,
};
매직 메소드 get/set
로 액세스할 수 있는 클래스 속성(이제 PSR 1 camelCase)
ez_mysqli
의 select
dbSelect
로 변경했습니다.
클래스 메소드 이름과 selecting
동작을 select
.
selecting
및 새로운 inserting
방법은 테이블 이름 없이 호출할 수 있으며 다른 필수 매개변수만 호출할 수 있습니다.
tableSetup(name, prefix), or setTable(name), setPrefix(append)
메소드를 사용하여 사전 설정/저장할 수 있습니다. 사전 설정 없이 호출하면 false
반환됩니다.ing
끝이 추가됩니다. table
이름이 전달된 전역 함수를 제거했습니다. ing
으로 끝나는 사전 설정된 테이블 이름을 사용하는 함수를 사용하세요.
cleanInput의 이름이 clean_string으로 변경되었습니다.
createCertificate의 이름이 create_certificate로 변경되었습니다.
다양한 형식으로 결과 세트를 반환하기 위해 전역 get_results를 추가했습니다.
버전 4 에는 버전 3의 사용자를 방해할 수 있는 최신 프로그래밍 방식이 많이 포함되어 있습니다.
버전 3은 한 가지 주요 방식으로 버전 2.1.7을 깨뜨렸는데, PHP 5.6이 필요했습니다. mysql 확장 지원을 중단하는 것 외에는 라이브러리 사용에 있어서는 아무것도 변경되지 않았으며 추가 기능만 변경되었습니다.
이 라이브러리에는 팩토리 패턴과 종속성 주입 컨테이너 호스팅이 결합된 Database
클래스가 있습니다. 이 라이브러리는 이제 많은 OOP 원칙을 따르고 있으며 그 중 하나는 메소드 속성 공개 액세스가 제거되었습니다. 이 라이브러리는 또한 PSR-2, PSR-4, PSR-11 규칙 및 대부분 PSR-1을 따르며 아직 진행 중인 작업입니다.
전체 개요를 보려면 완전히 끝나지 않은 문서 Wiki를 참조하세요.
composer require ezsql/ezsql
require ' vendor/autoload.php ' ;
// **** is one of mysqli, pgsql, sqlsrv, sqlite3, or Pdo.
use ezsql Database ;
$ db = Database:: initialize ( ' **** ' , [ $ dsn_path_user , $ password , $ database , $ other_settings ], $ optional_tag );
// Is same as:
use ezsql Config ;
use ezsql Database ez_ ****;
$ settings = new Config ( ' **** ' , [ $ dsn_path_user , $ password , $ database , $ other_settings ]);
$ db = new ez_ ****( $ settings );
이 라이브러리는 개발자가 Intellisense가 활성화된 일종의 IDE를 사용하고 있다고 가정합니다. 주석/문서 블록 영역에는 누락된 문서가 보관됩니다. 추가 예제를 보려면 phpunit 테스트를 참조하세요. 테스트는 완전한 기능을 갖춘 통합 테스트입니다. 즉, 모의 테스트가 아닌 실시간 데이터베이스 테스트입니다.
버전 2.1.7부터 다음이 추가되었습니다.
일반적인 방법
to_string($arrays, $separation = ',');
clean($string);
create_cache(string $path = null);
secureSetup(string $key = 'certificate.key',
string $cert = 'certificate.crt',
string $ca = 'cacert.pem',
string $path = '.'._DS
);
secureReset();
create_certificate(string $privatekeyFile = certificate.key,
string $certificateFile = certificate.crt,
string $signingFile = certificate.csr,
string $ssl_path = null, array $details = [commonName => localhost]
);
바로가기 테이블 방법
create(string $table = null, ...$schemas);// $schemas requires... column()
column(string $column = null, string $type = null, ...$args);
primary(string $primaryName, ...$primaryKeys);
index(string $indexName, ...$indexKeys);
drop(string $table);
예
// Creates an database table
create ( ' profile ' ,
// and with database column name, datatype
// data types are global CONSTANTS
// SEQUENCE|AUTO is placeholder tag, to be replaced with the proper SQL drivers auto number sequencer word.
column ( ' id ' , INTR , 11 , AUTO , PRIMARY ), // mysqli
column ( ' name ' , VARCHAR , 50 , notNULL),
column ( ' email ' , CHAR , 25 , NULLS ),
column ( ' phone ' , TINYINT )
);
innerJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
leftJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
rightJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
fullJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
prepareOn (); // When activated will use prepare statements for all shortcut SQL Methods calls.
prepareOff (); // When off shortcut SQL Methods calls will use vendors escape routine instead. This is the default behavior.
having(...$having);
groupBy($groupBy);
union(string $table = null, $columnFields = '*', ...$conditions);
unionAll(string $table = null, $columnFields = '*', ...$conditions);
orderBy($orderBy, $order);
limit($numberOf, $offset = null)
where( ...$whereConditions);
select(string $table = null, $columnFields = '*', ...$conditions);
create_select(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
select_into(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
update(string $table = null, $keyAndValue, ...$whereConditions);
delete(string $table = null, ...$whereConditions);
replace(string $table = null, $keyAndValue);
insert(string $table = null, $keyAndValue);
create(string $table = null, ...$schemas);
drop(string $table = null);
alter(string $table = null, ...$alteringSchema);
insert_select(string $toTable = null, $toColumns = '*', $fromTable = null, $fromColumns = '*', ...$conditions);
// The variadic ...$whereConditions, and ...$conditions parameters,
// represent the following global functions.
// They are comparison expressions returning an array with the given arguments,
// the last arguments of _AND, _OR, _NOT, _andNOT will combine expressions
eq ( ' column ' , $ value , _AND ), // combine next expression
neq ( ' column ' , $ value , _OR ), // will combine next expression again
ne ( ' column ' , $ value ), // the default is _AND so will combine next expression
lt ( ' column ' , $ value )
lte ( ' column ' , $ value )
gt ( ' column ' , $ value )
gte ( ' column ' , $ value )
isNull ( ' column ' )
isNotNull ( ' column ' )
like ( ' column ' , ' _%? ' )
notLike ( ' column ' , ' _%? ' )
in ( ' column ' , ... $ value )
notIn ( ' column ' , ... $ value )
between ( ' column ' , $ value , $ value2 )
notBetween ( ' column ' , $ value , $ value2 )
// The above should be used within the where( ...$whereConditions) clause
// $value will protected by either using escape or prepare statement
// To allow simple grouping of basic $whereConditions,
// wrap the following around a group of the above comparison
// expressions within the where( ...$whereConditions) clause
grouping ( eq (key, value, combiner ), eq (key, value, combiner ) )
// The above will wrap beginning and end grouping in a where statement
// where required to break down your where clause.
// Note: The usage of this method will require the user/developer to check
// if `query_string` or `param_array` is valid.
//
// This is really an `private` internal method for other shortcut methods,
// it's made public for `class development` usage only.
//
//
// Supply the the whole `query` string, and placing '?' within, with the same number of arguments in an array.
// It will then determine arguments type, execute, and return results.
query_prepared (string $ query_string , array $ param_array );
// You will need to call this method to get last successful query result.
// It wll return an object array.
queryResult ();
// To get all shortcut SQL methods calls to use prepare statements
$ db -> prepareOn (); // This needs to be called at least once at instance creation
$ values = [];
$ values [ ' name ' ] = $ user ;
$ values [ ' email ' ] = $ address ;
$ values [ ' phone ' ] = $ number ;
$ db -> insert ( ' profile ' , $ values );
$ db -> insert ( ' profile ' , [ ' name ' => ' john john ' , ' email ' => ' john@email ' , ' phone ' => 123456 ]);
// returns result set given the table name, column fields, and ...conditions
$ result = $ db -> select ( ' profile ' , ' phone ' , eq ( ' email ' , $ email ), between ( ' id ' , 1 , $ values ));
foreach ( $ result as $ row ) {
echo $ row -> phone ;
}
$ result = $ db -> select ( ' profile ' , ' name, email ' ,
// Conditionals can also be called, stacked with other functions like:
// innerJoin(), leftJoin(), rightJoin(), fullJoin()
// as (leftTable, rightTable, leftColumn, rightColumn, tableAs, equal condition),
// where( eq( columns, values, _AND ), like( columns, _d ) ),
// groupBy( columns ),
// having( between( columns, values1, values2 ) ),
// orderBy( columns, desc ),
// limit( numberOfRecords, offset ),
// union(table, columnFields, conditions),
// unionAll(table, columnFields, conditions)
$ db -> where ( eq ( ' phone ' , $ number , _OR ), neq ( ' id ' , 5 ) ),
// another way: where( array(key, operator, value, combine, combineShifted) );
// or as strings double spaced: where( "key operator value combine combineShifted" );
$ db -> orderBy ( ' name ' ),
$ db -> limit ( 1 )
);
foreach ( $ result as $ row ) {
echo $ row -> name . ' ' . $ row -> email ;
}
// To get results in `JSON` format
$ json = get_results ( JSON , $ db );
$ db -> query_prepared ( ' INSERT INTO profile( name, email, phone) VALUES( ?, ?, ? ); ' , [ $ user , $ address , $ number ]);
$ db -> query_prepared ( ' SELECT name, email FROM profile WHERE phone = ? OR id != ? ' , [ $ number , 5 ]);
$ result = $ db -> queryResult (); // the last query that has results are stored in `lastResult` protected property
// Or for results in other formats use the global function, will use global database instance if no `$db` supplied
$ result = get_results ( / * OBJECT | ARRAY _ A | ARRAY _ N | JSON */ , $ db ); // Defaults to `OBJECT`
foreach ( $ result as $ row ) {
echo $ row -> name . ' ' . $ row -> email ;
}
대부분의 단축 메소드에는 카운터 전역 기능을 사용할 수 있습니다. 다음과 같이 .php
파일을 시작해야만 액세스할 수 있습니다.
use function ezsql functions functionBelow ;
// Or as here, a complete list.
use function ezsql functions {
database ,
mysqlInstance ,
pgsqlInstance ,
mssqlInstance ,
sqliteInstance ,
pdoInstance ,
tagInstance ,
setInstance ,
getInstance ,
clearInstance ,
get_vendor ,
///
to_string ,
clean_string ,
is_traversal ,
sanitize_path ,
create_certificate ,
///
column ,
primary ,
foreign ,
unique ,
index ,
addColumn ,
dropColumn ,
changingColumn ,
///
eq ,
neq ,
ne ,
lt ,
lte ,
gt ,
gte ,
isNull ,
isNotNull ,
like ,
in ,
notLike ,
notIn ,
between ,
notBetween ,
///
where ,
grouping ,
groupBy ,
having ,
orderBy ,
limit ,
innerJoin ,
leftJoin ,
rightJoin ,
fullJoin ,
union ,
unionAll ,
///
creating ,
deleting ,
dropping ,
replacing ,
selecting ,
inserting ,
altering ,
get_results ,
table_setup ,
set_table ,
set_prefix ,
select_into ,
insert_select ,
create_select ,
};
함수 사용법/문서는 ezFunctions.php를 참조하세요.
기여를 장려하고 환영합니다. 나는 항상 Github에서 피드백이나 풀 요청을 받는 것을 기쁘게 생각합니다. :) 버그 및 새로운 기능에 대한 Github 문제를 만들고 관심 있는 항목에 대해 의견을 제시하세요.
ezsql 은 원래 LGPL-3.0에 따라 라이선스가 부여된 오픈 소스 소프트웨어이며, 애드온 부분은 MIT에 따라 라이선스가 부여되었습니다.