PHPackages                             sigma/build-query - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. sigma/build-query

ActiveLibrary[Database &amp; ORM](/categories/database)

sigma/build-query
=================

A php build query using pdo. Databases available Mysql, Postgres, Firebird, SQlite

214PHP

Since May 18Pushed 6y ago1 watchersCompare

[ Source](https://github.com/nathanfeitoza/sigmaBuildQuery)[ Packagist](https://packagist.org/packages/sigma/build-query)[ RSS](/packages/sigma-build-query/feed)WikiDiscussions master Synced yesterday

READMEChangelog (1)DependenciesVersions (2)Used By (0)

[![Build Status](https://camo.githubusercontent.com/27813b243c3c01b2f85d3ca5e7b936e82b1ac5f137d9cdab8095cb60efb10edb/68747470733a2f2f7472617669732d63692e6f72672f6e617468616e666569746f7a612f7369676d614275696c6451756572792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/nathanfeitoza/sigmaBuildQuery)

**SigmaBuildQuery** `beta`

A build query php to make SQL executions easier by standardizing them. Databases available: Mysql, Postgres, Firebird, Sqlite

To start BuildQuery, just make the following call:

```
 $var = new Sigma\BuildQuery( (string) 'driver',(string) 'host',(string) 'database',(string) 'user',(string) 'pass'[, (array) options);
```

After doing this, we have the method of executing SQL scripts (handwritten SQL)

```
 $var->executarSQL( (string) query, (array) campos [, (boolean) use_transaction, (boolean) use_exception_not_found] );
```

If use\_transaction is set to true, it will begin to use database transactions (which have this option: Firebird tested so far) The methods of querybuilder are shown below: Note: The use of the entire query builder is done via polymorphism, which are being shown below. The choice by this method has been established because it looks more like sql queries and block building of codes. Therefore, it facilitates the life of the developer, being that the order of the elements will not change the final result, unless a main element such as -&gt; table (string) is missing, but this check is already done and triggered in the log (to be implemented)

```
         $var->roolback() // Rollback if there is any open transaction. Can be used when mixing code with transaction with no transaction. Obs: Does not polymorphism because it is a method of containment / prevention of errors

         $var->tabela('teste') // Sets the usage table
         ->campos(array("terste1","teste2","teste3")) // Fields used to make select, one can only pass an empty array: [''], and it will search all the fields of the table, or ['*'], or the field names
         ->campos(array("terste1","teste2","teste3"),array("valor1","valor2","valor3")) // Fields and their respective values to be inserted or updated
         ->insertSelect("testar",array("campo1","campo2")) // To make an insert using a select, insert test set (select field1, field2 from table1)
         ->leftjoin("tabela b","a.id = b.id") // To use left join
         ->rightjoin("tabela b","a.id = b.id") // To use right join
         ->innerjoin("tabela b","a.id = b.id") // To use inner join
         ->fullouterjoin("tabela b","a.id = b.id") // To use full outer join
         ->where("teste","=",123) // For where use, where the first method is the fields, the second the comparative and the third the value to be compared
         ->whereComplex(array("testaco","testinho","testar","testei"),array("=","!=","=","!="),array("456","789","856","1"),array("OR", "AND","OR","OR")) // For a where with multiple attributes. Ex: WHERE (field = 1) AND (field2 = 3) OR (fields3 = 2)
         ->whereComplex(array("testaco","testinho","testar"),array("=","!=","="),array("456","789","856"),array("OR", "AND","OR"))
         ->whereOr("testar","!=",456) // The same as Where, but put the OR in front, this way, where it should be called before, otherwise it will cause an sql error
         ->whereAnd("testando","=",321) // Same as whereOr, however add the And
         ->groupby("tabelinha1") // To use groupby
         ->groupbyHaving("tabelinha1","teste = teste") // To use GROUP BY HAVING
         ->orderby("id","ASC") // For sorting, where the first method is the field and the second sorting type
         ->setGerarLog(true) // To generate logs with the execution query in the database -> true or false (Making)
         ->limit((int) 100 [,(int) offset]) // To add a limit and also offset (offset only in postgres) to the search (functional only in mysql and postgres)
         ->setUsarExceptionNaoEncontrado(true) // To trigger an exception if no result is found in a select, if true. If false, it will fire an array of two elements, the first containing a string saying nothing was found, and the second with error code (710). By default it is true
         ->buildQuery("select", true) // This method executes the query, being defined as: buildQuery ((string) exec_type, (boolean) usar_union, (boolean) usar_transaction). The first one refers to the type of call that will be made: select, update, delete, insert
         ->union('all') // To make the union between two tables. It allows its use by setting 'all', 'union' or empty. To work, it is necessary that the previous buildQuery is set to use_union
         ->tabela("teste3")
         ->campos(array("testar"), array("testarV"))
         ->buildQuery("select", true)
         ->union()
         ->commit() // Commit a transaction
         ->rollback() // Rollback a transacation
         ->tabela("teste4")
         ->campos(array("testar","testarheuhe"), array("testarV","testeF"))
         ->setRetornarLinhasAfetadas() // Count affected lines (for update, delete and insert)
         ->setRetornoPersonalizado($retorno) // Personalizated return
         ->buildQuery("select");
         ->camposDdlCreate([], $primary_key = false); // To create DDL Fields
         ->setEngineMysql($engine); // Set Mysql Engine
         ->showTables(); // Show tables in db
         ->setDefaultCharacter($caracter); // Se Default Character for create or alter table
         ->setCollate($collate); // Set collate to table
         ->createTable(); // To create a table
         ->dropTable(); // To drop a table
```

Example using simple transaction

```
     $total = 3;
     $var->inicarTransacao(); // Is necessary for maintaining the PDO Object ans init the transaction
     for($i = 0; $i < $total; $i++) {
         $dados_add = $i;
         $data = $var
             ->tabela('teste')
             ->campos(['log','testei'], ['teste-'.$i,$dados_add])
             ->setGerarLog(true)
             ->buildQuery('insert');
     }
     $var->commit(); // To commit the transaction
     /*
     Or use: $var->rollback() // To rollback the transaction
     */
```

Example using multiples tables with transactions

```
     $var->inicarTransacao();
     for($i = 0; $i < 100; $i++) {
         $data = $var->tabela('teste')
             ->campos(['log','testei'], ['teste-'.$i, 1])
             ->setGerarLog(true)
             ->buildQuery('insert', true)
             ->tabela('teste2')
             ->campos(['nome','teste'], ['teste_tabela2-'.$i, 1])
             ->setGerarLog(true)
             ->buildQuery('insert');
     }

     $var->commit(); // To commit the transaction
     /*
     Or use: $var->rollback() // To rollback the transaction
     */
```

Varying number of values entered in table 2

```
     $percorrer = 100;
     $var->inicarTransacao();
     $data = $var->tabela('teste')
         ->campos(['log','testei'], ['teste-0', 1])
         ->setsetGerarLog(true)
         ->buildQuery('insert', true);
     for($i = 0; $i < $percorrer; $i++) {
             $add = 1;
             $data->tabela('teste2')
             ->campos(['nome','teste'], ['teste_tabela2-'.$i, $add])
             ->setGerarLog(true);

             $data->buildQuery('insert', ($i+1) < $percorrer);

     }

     $var->commit(); // To commit the transaction
     /*
     Or use: $var->rollback() // To rollback the transaction
     */
```

Use log complex or events in database

```
     $var->setEventosGravar(['INSERT','DELETE','UPDATE'])->setLogComplexo = function($con, $acao) {

     };
```

DDL comands
===========

[](#ddl-comands)

Create Table
------------

[](#create-table)

Create table use this example below.

```
  $var->tabela('teste123')
       ->camposDdlCreate([
       'id' => [
            'type' => 'int',
            'options_field' => ['NOT NULL']
       ],
       'nome' => [
            'type' => 'TINYTEXT',
            'options_field' => ['NOT NULL']
       ]
       ], 'id')
     ->setEngineMysql('InnoDB')
     ->setGerarLog(true)
     ->createTable();

  // Create table with foreign key (alpha)

  $var->tabela('teste123')
       ->camposDdlCreate([
       'id' => [
            'type' => 'int',
            'options_field' => ['NOT NULL']
       ],
       'nome' => [
            'type' => 'TINYTEXT',
            'options_field' => ['NOT NULL']
       ]
       ], 'id')
     ->setEngineMysql('InnoDB')
     ->campos(['id'])
     ->setForeignKey('teste_fk', ['tabela' => 'teste123', 'campos' => ['id']])
     ->setGerarLog(true)
     ->createTable();
```

Drop Table
----------

[](#drop-table)

```
  $var->tabela('teste123')->dropTable();
```

Create View
-----------

[](#create-view)

Create view use this example below.

```
$var->tabela('teste')
     ->campos(['*'])
     ->buildQuery('select', true)
     ->createView('view_teste');
```

Drop View
---------

[](#drop-view)

```
  $var->dropView('view_teste');
```

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/c7023322565441ff2bc9e0b48fd8d94135bd2d85ecff5c04cddca64ed37d0c1f?d=identicon)[nathanfeitoza](/maintainers/nathanfeitoza)

---

Top Contributors

[![nathanfeitoza](https://avatars.githubusercontent.com/u/37680036?v=4)](https://github.com/nathanfeitoza "nathanfeitoza (58 commits)")

### Embed Badge

![Health badge](/badges/sigma-build-query/health.svg)

```
[![Health](https://phpackages.com/badges/sigma-build-query/health.svg)](https://phpackages.com/packages/sigma-build-query)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
