PHPackages                             lq80/db - 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. lq80/db

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

lq80/db
=======

simple query builder class in PHP

011PHP

Since Sep 13Pushed 7y ago1 watchersCompare

[ Source](https://github.com/LQ80/DB)[ Packagist](https://packagist.org/packages/lq80/db)[ RSS](/packages/lq80-db/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependenciesVersions (1)Used By (0)

Welcome to Marei's DB class V 1.0
=================================

[](#welcome-to-mareis-db-class-v-10)

MareiDB class is a simple query builder class in PHP to increase your productivity, you can't imagine how much time you're gonna save if you're using this class! .

Features
--------

[](#features)

- Totally Secured : This DB class uses PDO prepared statements to provide high levels of protection against SQL Injection attacks
- Easy Usage : The syntax is really simple, and there are many ways to do the same query, so you can use the way you like ;)
- Well Documented : Everything you wanna know about this class is here and organized very well, so you can find it easily.

Usage
-----

[](#usage)

After downloading the class from [here](https://raw.githubusercontent.com/mareimorsy/DB/master/DB.php) save it into your root directory and then open it to adjust the basic configurations for your DB connection like host, database name, DB username and DB password. And also you can easily define your current development environment to `development` or `production`.

```
//current development environment
"env" => "development",
//Localhost
"development" => [
					"host" => "localhost",
					"database" => "test",
					"username" => "root",
					"password" => ""
				 ],
//Server
"production"  => [
					"host" => "",
					"database" => "",
					"username" => "",
					"password" => ""
				 ]
```

To use the class, just include it into your project files like this

```
include 'DB.php';
```

Then you have to instantiate the class like this

```
$db = DB::getInstance();
```

Now, `$db` object is a new instance of DB class, we're gonna use this object to deal with our database, and you can create many objects as you want (don't worry about connections because i'm using Singleton design pattern so whenever you create new objects it returns the same connection) .

### Insert values to a table

[](#insert-values-to-a-table)

use the `insert()` method to insert values to a table, and it takes 2 parameters : the first one is `$table_name` and the second one is an associative array `$fields[]` so the key of that array is the column name in the table and the value of that array is the value that you wanna insert at that column.

```
$db->insert('mytable',
	[
		'first_name' => 'Marei',
		'last_name' => 'Morsy',
		'age'	=> 22
	]);
```

To see the SQL query that have executed, use the `getSQL()` Method like this:

```
echo $db->getSQL();
```

Output :

```
INSERT INTO `mytable` (`first_name`, `last_name`, `age`) VALUES (?, ?, ?)
```

#### Get the last ID inserted :

[](#get-the-last-id-inserted-)

You can get the last ID inserted using `lastId()` method, or you can get the return of `insert()` method like this :

```
$lastID = $db->insert('mytable',
	[
		'first_name' => 'Marei',
		'last_name' => 'Morsy',
		'age'	=> 22
	]);
echo $lastID;
```

And here is how to use `lastId()` after using `update()` method :

```
echo $db->lastId();
```

### Update table values

[](#update-table-values)

To update the table use `update()` method it holds 3 parameters : the first one is the table name, the second one is an associative array of the table values that you wanna update and the third parameter is optional, you can use it to state the update condition like WHERE clause in SQL. DB class provides so many ways to do the same queries for example : the third parameter in `update()` method you can do one of the following methods : ####Passing the id You can pass the `$id` as a third parameter and DB class will understand that there's a field in the table called `id` and you wanna update the record that its id is the value of `$id` like this :

```
$db->update('mytable',
	[
		'first_name' => 'Mohammed',
		'last_name' => 'Gharib',
		'age'	=> 24
	],1);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ?
```

but, what if the column name was not id? ####Passing the column name and value you can pass an array of two items to `update` method as a third parameter : the first item in the array is the column name and the second item is the column value. The `update()` method in DB class will understand that you wanna update the table where the column name is equal to the value. Like this :

```
$db->update('mytable',
	[
		'first_name' => 'Ahmed',
		'last_name' => 'Hendy',
		'age'	=> 23
	],['id',1]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ?
```

but, what if we need to use another operator? ####Passing column name, operator and value You can pass an array of three items to `update()` method as a third parameter.The first item of the array is the column name as string, the second one is the operator as a string and the third item is the value, like this :

```
$db->update('mytable',
	[
		'first_name' => 'Zizo',
		'last_name' => 'Atia',
		'age'	=> 23
	],['age','>',22]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`age` > ?
```

you can also do the same query by only 2 items in the array like this :

```
$db->update('mytable',
	[
		'first_name' => 'Ahmed',
		'last_name' => 'Mansour',
		'age'	=> 27
	],['age >= ',22]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE age >= ?
```

but, what if we wanna add more than one where condition? ####passing more than one where condition You can pass an array of arrays(nested array) as a third parameter to `update()` method, each array holds three items : the column name as a string, the operator and the value. The second and the third items are optional, so you can pass only the id as an array, or you can pass an array of two items : the column name and the value. And here is some examples of passing an array :

##### Example 1 :

[](#example-1-)

```
$db->update('mytable',
	[
		'first_name' => 'Omar',
		'last_name' => 'Saqr',
		'age'	=> 23
	],[ [1] ]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ?
```

##### Example 2 :

[](#example-2-)

```
$db->update('mytable',
	[
		'first_name' => 'Ahmed',
		'last_name' => 'Helmy',
		'age'	=> 21
	],[ ['age',18], [1] ]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`age` = ? AND `mytable`.`id` = ?
```

##### Example 3 :

[](#example-3-)

```
$db->update('mytable',
	[
		'first_name' => 'Ahmed',
		'last_name' => 'Ashraf',
		'age'	=> 21
	],[ ['age','>=', 18], [1] ]);
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`age` >= ? AND `mytable`.`id` = ?
```

Or you can do `[ ['age >= ', 18], [1] ]` to get the same result.

### Another way to update using `where()` method

[](#another-way-to-update-using-where-method)

`where()` method holds three parameters the second and the third are optional, if you passed only one parameter, the `where()` method will understand that there's a field called id and you wanna update the table where its id equals to that parameter like this :

```
$db->update('mytable',
	[
		'first_name' => 'Ashraf',
		'last_name' => 'Hefny',
		'age'	=> 28
	])->where(1)->exec();
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ?
```

We use `exec()` method to execute the query, that means you can use `getSQL()` method to check the query before you execute it without `exec()`. You can use more than one `where()` method the same way like this :

```
$db->update('mytable',
	[
		'first_name' => 'Osama',
		'last_name' => 'El-Zero',
		'age'	=> 30
	])->where(1)->where('first_name','Ashraf')->exec();
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ? AND `mytable`.`first_name` = ?
```

As you see, if you provide the where method with 2 parameters it will understand that you wanna update the table where the column name is the first parameter where it is equal to the value of the second parameter. And also if you noticed that the second where becomes 'AND' in the query.

```
$db->update('mytable',
	[
		'first_name' => 'Ali',
		'last_name' => 'Hamdy',
		'age'	=> 30
	])->where(1)->where('age','>',20)->exec();
```

SQL Query :

```
UPDATE `mytable` SET `first_name` = ?, `last_name` = ?, `age` = ? WHERE `mytable`.`id` = ? AND `mytable`.`age` > ?
```

Now what if we wanted to add OR to our where clause? ###How to use `orWhere()` method? `orWhere()` acts exactly like `where()` method and it takes the same parameters it's like 'OR' in SQL and you can use both methods together like this :

```
$db->update('mytable',
	[
		'first_name' => 'Muhammad',
		'last_name' => 'Mustafa',
		'age'	=> 21
	])->where('age','=', 18], [1] ])->exec();
```

SQL would be like this :

```
WHERE `first_name` = ? AND age >= ? AND id = ?
```

You can also use a combination of `where()` and `orWhere()` methods whith single caluse or with a group of where clauses like this :

```
->where([ ['first_name', 'Marei'], ['age >=', 18]])->where(1)->orWhere([ [5], ['last_name', 'Morsy'] ])->exec();
```

SQL would be like this :

```
WHERE `first_name` = ? AND age >= ? AND `id` = ? OR `id` = ? Or `last_name` = ?
```

As you notice that you can use `where()` and `orWhere()` not only with `upadte()` method, but also with other query methods such as `delete()`, `update()` and `table()`. ###Delete values from table use `delete()` method to delete rows from table, it holds 2 parameters, the first one is table name and the second one is optional, it acts exactly like the third parameter in `update()` method so, you can pass only the id as integer value, you can pass an array of the field name and the value, you can pass an array of the field name and parameter and value, you can pass an array of arrays of where clauses. And here are some examples of how to use `delete()` method : ####Example 1 :

```
$db->delete('mytable',1);
```

SQL Query :

```
DELETE FROM `mytable` WHERE `mytable`.`id` = ?
```

\####Example 2 :

```
$db->delete('mytable', ['first_name', 'Marei']);
```

SQL Query :

```
DELETE FROM `mytable` WHERE `mytable`.`first_name` = ?
```

\####Example 3 :

```
$db->delete('mytable', ['age', 'table("users")->get()->toList('token') );
```

print all tokens in the users table as an array

#### `Qget()` Method :

[](#qget-method-)

`Qget()` method works exactly like get method but without all `MareiCollecton` functionality like print the result as JSON and other methods like `toArray()`, `toJSON()`, `first()`, `last()` and `item()`. if you really care about performance `Qget()` is what you need to use. And you can use it like this :

```
$users = $db->table("users")->Qget();
foreach ($users as $user) {
	echo $user->first_name;
}
```

To print the result of `Qget()` as JSON just use `json_encode($Qget_result);` like this :

```
$users = $db->table("users")->Qget();
echo json_encode($users);
```

#### `select()` Method :

[](#select-method-)

If you want to select a specific column(s) use `select()` method, it holds column names as a string parameter separated by `,` like this :

```
$rows = $db->table('mytable')->select('first_name, last_name')->get();
```

SQL Query :

```
SELECT `first_name`, `last_name` FROM `mytable`
```

#### `limit()` Method :

[](#limit-method-)

The `limit()` method makes it easy to code multi page results or pagination, and it is very useful on large tables. Returning a large number of records can impact on performance. It takes two parameters the first one is used to specify the number of records to return. And the second one is optional to pass the offset. And you can use it like this :

```
$rows = $db->table('mytable')->limit(10)->get();
```

SQL Query :

```
SELECT * FROM `mytable` LIMIT 10
```

It will return the first 10 records.

```
$rows = $db->table('mytable')->limit(10, 20)->get();
```

SQL Query :

```
SELECT * FROM `mytable` LIMIT 10 OFFSET 20
```

It will return only 10 records, start on record 21 (OFFSET 20).

#### Easy pagination with `paginate()` method :

[](#easy-pagination-with-paginate-method-)

Now after using `paginate()` method, pagination has never been easier!. You can use `paginate()` method with all selection methods like `table()` and `select()` instead of `get()`, it takes two parameters : the first one is page number starting from 1 as integer and the second one is used to specify the number of records to return `paginate($page, $limit)` and you can use it exactly like `get()` method and here is an example of how you can use it :

```
$rows = $db->table('mytable')->paginate(2, 5);
```

That means we want to return only 5 records from the second page and it will return only 5 records, start on record 6 up to 10. To get more information about what is going on behind the scenes, use `PaginationInfo()` method for more details like this:

```
print_r( $db->paginationInfo() );
```

Output :

```
Array
(
    [previousPage] => 1
    [currentPage] => 2
    [nextPage] => 3
    [lastPage] => 5
)

```

It will return an associative array of useful information you might need to know like the current, previous, next and last page. And if there's no previous or next page its value would be null.

#### `Qpaginate()` Method :

[](#qpaginate-method-)

`Qpaginate()` method works exactly like `paginate()` method but without all `MareiCollecton` functionality like print the result as JSON and other methods like `toArray()`, `toJSON()`, `first()`, `last()` and `item()`. if you really care about performance `Qget()` is what you need to use. And you can use it like this :

```
$rows = $db->table('mytable')->paginate(2, 5);
```

\####Using `where()` and `orWhere()` with selection : You can use `where()` or `orWhere()` methods with selection like this :

```
$rows = $db->table('mytable')->where(1)->get();
```

SQL Query :

```
SELECT * FROM `mytable` WHERE `mytable`.`id` = ?
```

\####Order the result set you can use `orderBy()` method to order the result set by a column name, `orderBy($column_name, $order)` takes two parameters, the first one is the column name as string and the second one is optional and it takes only two values `ASC` which is the default value to order the result set by asccending order, or `DESC` to order the result set by descending order like this :

```
$rows = $db->table('mytable')->orderBy('id', 'DESC')->get();
```

To order the result set in descending order by id. And you can use more than orderBy together like this :

```
$rows = $db->table('mytable')
           ->orderBy('id', 'DESC')
	   ->orderBy('age', 'ASC')
	   ->get();
```

and ofcourse as you use `orderBy()` with `get()`, you can also use it with `paginate()`, `limit()`, `Qget()` and `Qpaginate()` methods. ####Count selected rows Use `getCount()` method to get the total number of rows returned of the last query. and you can use it after selection like this :

```
echo $db->getCount();
```

\###Using Raw Queries : I bet that you asked what if I wanted to execute more complected queries? that's why I created `query()` method, it holds three parameters the first one is SQL query as a string, and the second one is optional and it's for the values that you wanna pass to query as an array. And here is how you can use `query()` method :

```
$sql = "SELECT * FROM mytable WHERE id = ?";
$rows = $db->query($sql, [1]);
```

SQL Query :

```
SELECT * FROM mytable WHERE id = 1
```

if you want to get rid of all `MareiCollection` functionally just pass true as a third parameter like this :

```
$sql = "SELECT * FROM mytable WHERE id = ?";
$rows = $db->query($sql, [1], true);
```

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 55.3% 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/1c179d0652859bd7d0c6766f6f3c881ac47189b0b5eab34c206bec3fc1a7fafc?d=identicon)[LQ80](/maintainers/LQ80)

---

Top Contributors

[![mareimorsy](https://avatars.githubusercontent.com/u/11376730?v=4)](https://github.com/mareimorsy "mareimorsy (21 commits)")[![LQ80](https://avatars.githubusercontent.com/u/6532303?v=4)](https://github.com/LQ80 "LQ80 (13 commits)")[![ahmedash95](https://avatars.githubusercontent.com/u/8272048?v=4)](https://github.com/ahmedash95 "ahmedash95 (4 commits)")

### Embed Badge

![Health badge](/badges/lq80-db/health.svg)

```
[![Health](https://phpackages.com/badges/lq80-db/health.svg)](https://phpackages.com/packages/lq80-db)
```

###  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)
