PHPackages                             maplephp/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. maplephp/query

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

maplephp/query
==============

MaplePHP - MySQL queries is a powerful yet user-friendly library for making safe database queries

v2.0.2(1y ago)2119[1 PRs](https://github.com/MaplePHP/Query/pulls)1Apache-2.0PHPPHP &gt;=8.0

Since Nov 29Pushed 6mo ago2 watchersCompare

[ Source](https://github.com/MaplePHP/Query)[ Packagist](https://packagist.org/packages/maplephp/query)[ Docs](https://wazabii.se)[ RSS](/packages/maplephp-query/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (14)Used By (1)

MaplePHP - Database query builder
=================================

[](#maplephp---database-query-builder)

MaplePHP - Database query builder is a powerful yet **user-friendly** library for making **safe** database queries, with support for MySQL, SQLite and PostgreSQL.

### Contents

[](#contents)

- [Connect to the database](#connect-to-the-database)
- [Make queries](#make-queries)
- [Attributes](#attributes)
- [Multiple Connections](#multiple-connections)
- *Migrations (Coming soon)*

Connect to the database
-----------------------

[](#connect-to-the-database)

### Connect to MySQL

[](#connect-to-mysql)

```
use MaplePHP\Query\Connect;

$handler = new MySQLHandler(
    $server,
    $user,
    $password,
    $databaseName,
    $port = 3306
);

// Recommend: Set TABLE prefix. This will make your life easier
// MaplePHP will automatically prepend the prefix to the table names.
$handler->setPrefix("maple_");
$handler->setCharset("utf8mb4");
$connect = Connect::setHandler($handler);
$connect->execute();
```

### Connect to SQLite

[](#connect-to-sqlite)

```
use MaplePHP\Query\Connect;

$SQLiteHandler = new SQLiteHandler(__DIR__ . "/database.SQLite");
$SQLiteHandler->setPrefix("mp_");
$connect = Connect::setHandler($SQLiteHandler);
$connect->execute();
```

### Connect to PostgreSQL

[](#connect-to-postgresql)

```
use MaplePHP\Query\Connect;

$postgreSQLHandler = new PostgreSQLHandler($server, $user, $password, $databaseName, $port = 5432);
$postgreSQLHandler->setPrefix("mp_");
$connect = Connect::setHandler($postgreSQLHandler);
$connect->execute();
```

***Note:** That the first connection will count as the main connection if not overwritten. You can also have multiple connection, [click here](#multiple-connections) for more information.*

Make queries
------------

[](#make-queries)

Start with the namespace

```
use MaplePHP\Query\DB;
```

### Select 1:

[](#select-1)

```
$select = DB::select("id,firstname,lastname", ["users", "aliasA"])->whereId(1)->where("status", 0, ">")->limit(1);
$select->join(["login", "aliasB"], "aliasB.user_id = aliasA.id");
$obj = $select->get(); // Get one row result as object
```

*Default alias will be the table name e.g. users and login if they were not overwritten.*

### Select 2:

[](#select-2)

```
$select = DB::select("id,name,content", "pages")->whereStatusParent(1, 0);
$array = $select->fetch(); // Get all rows as an array
```

### Where 1

[](#where-1)

```
$select->where("id", 1); // id = '1'
$select->where("parent", 0, ">");  // parent > '1'
```

### Where 2

[](#where-2)

"compare", "or"/"and" and "not".

```
$select->whereRoleStatusParent(1, 1, 0);
// role = '1' AND status = '1' AND Parent = 0
$select->compare(">")->whereStatus(0)->or()->whereRole(1);
// status > '0' OR role = '1'
$select->not()->whereId(1)->whereEmail("john.doe@gmail.com");
// NOT id = '1' AND email = 'john.doe@gmail.com'
```

### Where 3

[](#where-3)

```
$select->whereBind(function($select) {
    $select
    ->where("start_date", "2023-01-01", ">=")
    ->where("end_date", "2023-01-14", "");  // parent > '1'
$select->havingRaw("status = 1 AND visible = 1");
$select->havingRaw("status = %d AND visible = %d", [1, 1]);
```

### Limit

[](#limit)

```
$select->limit(1); // LIMIT 1
$select->offset(2); // OFFSET 2
$select->limit(10, 2); // LIMIT 10 OFFSET 2
```

### Order

[](#order)

```
$select->order("id");
// ORDER BY price ASC
$select->order("price", "DESC");
// ORDER BY price DESC
$select->order("id", "ASC")->order("parent", "DESC");
// ORDER BY id ASC, parent DESC
$select->orderRaw("id ASC, parent DESC");
// ORDER BY id ASC, parent DESC
```

### Join

[](#join)

**Note** that no value in the join is, by default, enclosed. This means it will not add quotes to strings. This means it will attempt to add a database column by default if it is a string, and will return an error if the string column does not exist. If you want to enclose the value with quotes, use Attributes (see the section below).

```
$select->join(["login", "aliasB"], ["aliasB.user_id" => "aliasA.id"]); // PROTECTED INPUT

$select->join("login", ["user_id" => "id"]);
// user_id = id AND org_id = oid

// This will enclose and reset all protections
$slug = DB::withAttr("my-slug-value");
$select->join("login", [
    ["slug" => $slug],
    ["visible" => 1]
]);

$select->join("tableName", "b.user_id = '%d'", [872], "LEFT"); // PROTECTED INPUT
$select->join("tableName", "b.user_id = a.id"); // "UNPROTECTED" INPUT

$select->joinInner("tableName", ["b.user_id" => "a.id"]);
$select->joinLeft("tableName", ["b.user_id" => "a.id"]);
$select->joinRight("tableName", ["b.user_id" => "a.id"]);
$select->joinCross("tableName", ["b.user_id" => "a.id"]);
```

### Pluck

[](#pluck)

```
$select->pluck("a.name")->get();
```

### Insert

[](#insert)

```
$insert = DB::insert("pages")->set(["id" => 36, "name" => "About us", "slug" => "about-us"])->onDupKey();
$insert->execute(); // bool
$insertID = $select->insertID(); // Get AI ID
```

### Update on duplicate

[](#update-on-duplicate)

Will update row if primary key exist else Insert

```
$insert->onDupKey();
// Will update all the columns in the method @set
$insert->onDupKey(["name" => "About us"]);
// Will only update the column name
```

### Update

[](#update)

```
$update = DB::update("pages")->set(["name" => "About us", "slug" => "about-us"])->whereId(34)->limit(1);
$update->execute();
```

### Delete

[](#delete)

```
$delete = DB::delete("pages")->whereId(34)->limit(1);
$delete->execute();
```

### Set

[](#set)

```
$select->set("firstname", "John")->set("lastname", "Doe");
// Update/insert first- and last name
$select->set(["firstname" => "John", "lastname" => "Doe"])->set("lastname", "Doe");
// Same as above: Update/insert first- and last name
$select->setRaw("msg_id", "UUID()");
// UNPORTECTED and and will not be ENCLOSED!
```

### Preview SQL code before executing

[](#preview-sql-code-before-executing)

```
echo $select->sql();
```

Attributes
----------

[](#attributes)

Each value is automatically escaped by default in the most effective manner to ensure consequential and secure data storage, guarding against SQL injection vulnerabilities. While it's possible to exert complete control over SQL input using various **Raw** methods, such an approach is not advisable due to the potential for mistakes that could introduce vulnerabilities. A safer alternative is to leverage the **Attr** class. The **Attr** class offers comprehensive configuration capabilities for nearly every value in the DB library, as illustrated below:

```
$idValue = DB::withAttr("1")
    ->prep(true)
    ->enclose(true)
    ->encode(true)
    ->jsonEncode(true);

$select->where("id",  $idValue);
```

#### Escape values and protect against SQL injections

[](#escape-values-and-protect-against-sql-injections)

```
public function prep(bool $prep): self;
```

**Example:**

- Input value: Lorem "ipsum" dolor
- Output value: Lorem \\"ipsum\\" dolor

#### Enable/disable string enclose

[](#enabledisable-string-enclose)

```
public function enclose(bool $enclose): self;
```

**Example:**

- Input value: 1186
- Output value: '1186' *E.g. will add or remove quotes to values*

#### Enable/disable XSS protection

[](#enabledisable-xss-protection)

Some like to have the all the database data already HTML special character escaped.

```
public function encode(bool $encode): self;
```

**Example:**

- Input value: Lorem **ipsum** dolor
- Output value: Lorem &lt;strong&gt;ipsum&lt;/strong&gt; dolor

#### Automatically json encode array data

[](#automatically-json-encode-array-data)

A pragmatic function that will automatically encode all array input data to a json string

```
public function jsonEncode(bool $jsonEncode): self;
```

**Example:**

- Input value: array("firstname" =&gt; "John", "lastname" =&gt; "Doe");
- Output value: {"firstname":"John","lastname":"Doe"}

The default values vary based on whether it is a table column, a condition in a WHERE clause, or a value to be set. For instance, if expecting a table columns, the default is not to enclose value with quotes, whereas for WHERE or SET inputs, it defaults is to enclose the values. Regardless, every value defaults to **prep**, **encode** and **jsonEncode** being set to **true**.

Multiple connections
--------------------

[](#multiple-connections)

You can have multiple connection to different MySQL or SQLite databases or both.

```
use MaplePHP\Query\Connect;

// DB: 1
$handler = new MySQLHandler(
    $server,
    $user,
    $password,
    $databaseName,
    $port
);
$handler->setPrefix("maple_");
$handler->setCharset("utf8mb4");
$connect = Connect::setHandler($handler);
$connect->execute();

// DB: 2
$SQLiteHandler = new SQLiteHandler(__DIR__ . "/database.SQLite");
$SQLiteHandler->setPrefix("mp_");
$connect = Connect::setHandler($SQLiteHandler, "myConnKey");
$connect->execute();

// The connections have been made!
// Let's do some queries

// DB-1 Query: Access the default MySQL database
$select = DB::select("id,firstname,lastname", "users")->whereId(1)->limit(1);
$obj = $select->get();

// DB-2 Query: Access the SQLite database
$select = Connect::getInstance("myConnKey")::select("id,name,create_date", "tags")->whereId(1)->limit(1);
$obj = $select->get();
```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance52

Moderate activity, may be stable

Popularity13

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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.

###  Release Activity

Cadence

Every ~26 days

Recently: every ~62 days

Total

11

Last Release

638d ago

Major Versions

v1.1.2 → v2.0.02024-06-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/724b188e785081275926c5b9c07082e2b3f4afb797efdda61eb1630457e17824?d=identicon)[wazabii](/maintainers/wazabii)

---

Top Contributors

[![CreativeWaDev](https://avatars.githubusercontent.com/u/153771800?v=4)](https://github.com/CreativeWaDev "CreativeWaDev (4 commits)")[![danielRConsid](https://avatars.githubusercontent.com/u/169045496?v=4)](https://github.com/danielRConsid "danielRConsid (4 commits)")[![wazabii8](https://avatars.githubusercontent.com/u/6400238?v=4)](https://github.com/wazabii8 "wazabii8 (1 commits)")

---

Tags

databasemysqlquerymysqlifetch

### Embed Badge

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

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

###  Alternatives

[fpdo/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

921244.9k7](/packages/fpdo-fluentpdo)[sergeytsalkov/meekrodb

The Simple PHP/MySQL Library

341387.0k10](/packages/sergeytsalkov-meekrodb)[opis/database

A database abstraction layer over PDO, that provides a powerful and intuitive query builder, bundled with an easy to use schema builder

10184.2k3](/packages/opis-database)[go/db

Database library

6624.1k](/packages/go-db)[codesvault/howdy-qb

Mysql Query Builder for WordPress

371.2k1](/packages/codesvault-howdy-qb)[krugozor/database

PHP class library for simple, convenient, fast and safe work with MySql database, using PHP mysqli extension and imitation of prepared queries.

392.5k](/packages/krugozor-database)

PHPackages © 2026

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