Fast and Powerful SQL for PHP
If you're looking for something that is not an ORM but can generate SQL for you, you just found the right one., (*2)
Magsql is not an ORM (Object relational mapping) system, but a toolset that helps you generate cross-platform SQL queries in PHP., (*3)
Magsql is a stand-alone library, you can simply install it through composer or just require them (the class files) with your autoloader, and it has no dependencies., (*4)
Here is a short example of using Universal SelectQuery, (*5)
use Magsql\Universal\Query\SelectQuery; use Magsql\Driver\MySQLDriver; use Magsql\Driver\PgSQLDriver; use Magsql\Driver\SQLiteDriver; $mysql = new MySQLDriver; $args = new ArgumentArray; $query = new SelectQuery; $query->select(array('id', 'name', 'phone', 'address','confirmed')) ->from('users', 'u') ->partitions('u1', 'u2', 'u3') ->where() ->is('confirmed', true) ->in('id', [1,2,3]) ; $query ->join('posts') ->as('p') ->on('p.user_id = u.id') ; $query ->orderBy('rand()') ->orderBy('id', 'DESC') ; $sql = $query->toSql($mysql, $args); var_dump($sql); var_dump($args);
Unlike other SQL utilities, Magsql let you define the quote style and the parameter marker type. there are 2 parameter marker type you can choose:, (*6)
?
):id
, :name
, :address
, :p1
)The above two are supported by PDO directly, and the first one is also
supported by mysqli
, pgsql
extension., (*7)
The API is dead simple, easy to remember, you can just define one query, then pass different query driver to the query object to get a different SQL string for your targettting platform., (*8)
It also supports cross-platform query generation, there are three types of query (currently): Universal, MySQL, PgSQL. The Universal queries are cross-platform, you can use them to create a cross-platform PHP API of your database system, and the supported platforms are: MySQL, PgSQL and SQLite., (*9)
Universql Queries:, (*10)
To see the implementation details, you can check the source code inside Universal namespace: https://github.com/maghead/magsql/tree/master/Magsql/Universal/Query, (*11)
MySQL Queries:, (*12)
For MySQL platform, the implementation is according to the specification of MySQL 5.6., (*13)
For PostgreSQL platform, the implementation is according to the specification of PostgreSQL 9.2., (*14)
composer require corneltek/sqlbuilder
Documentation, (*15)
composer install
Copy the phpunit.xml
file for your local configuration:, (*16)
phpunit -c your-phpunit.xml tests
To test with mysql database:, (*17)
mysql -uroot -p CREATE DATABASE sqlbuilder CHARSET utf8; GRANT ALL PRIVILEGES ON sqlbuilder.* TO 'testing'@'localhost' identified by ''; --- or use this to remove password for testing account SET PASSWORD FOR testing@localhost=PASSWORD('');
To test with pgsql database:, (*18)
sudo -u postgres createdb sqlbuilder
Yo-An Lin (c9s) cornelius.howl@gmail.com, (*19)