PHPackages                             ceus-media/database - 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. ceus-media/database

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

ceus-media/database
===================

PHP database access

0.7.0(1mo ago)11.5k2GPL-3.0-or-laterPHPPHP ^8.3CI passing

Since Jul 13Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/CeusMedia/Database)[ Packagist](https://packagist.org/packages/ceus-media/database)[ RSS](/packages/ceus-media-database/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (16)Versions (25)Used By (2)

Database
========

[](#database)

[![Branch](https://camo.githubusercontent.com/38bc7fb86941ba6feecbe484e25bc5f14171a7d1381cc23cd10bcd2365ab4caa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4272616e63682d302e362e782d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/38bc7fb86941ba6feecbe484e25bc5f14171a7d1381cc23cd10bcd2365ab4caa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4272616e63682d302e362e782d626c75653f7374796c653d666c61742d737175617265)[![Release](https://camo.githubusercontent.com/09b2a642bdb4df0211a684be7e573861e3257a733f3ab09495e8861c44e44b02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f52656c656173652d302e362e362d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/09b2a642bdb4df0211a684be7e573861e3257a733f3ab09495e8861c44e44b02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f52656c656173652d302e362e362d626c75653f7374796c653d666c61742d737175617265)[![PHP version](https://camo.githubusercontent.com/7ebb0279547d526a54d318d9ab47d214fc6a36936050d77b00e120c3ce9db3f1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e312d626c75653f7374796c653d666c61742d73717561726526636f6c6f723d373737424234)](https://camo.githubusercontent.com/7ebb0279547d526a54d318d9ab47d214fc6a36936050d77b00e120c3ce9db3f1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e312d626c75653f7374796c653d666c61742d73717561726526636f6c6f723d373737424234)[![PHPStan level](https://camo.githubusercontent.com/1f80a1bbb21c16a059bdb6121960f1a181e966982bdf34570131a60cb6173cb4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e5f6c6576656c2d392b7374726963742d6461726b677265656e3f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/1f80a1bbb21c16a059bdb6121960f1a181e966982bdf34570131a60cb6173cb4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e5f6c6576656c2d392b7374726963742d6461726b677265656e3f7374796c653d666c61742d737175617265)[![Monthly downloads](https://camo.githubusercontent.com/ccdc130ecdcac0bcd66bb25d0eac7f19acf3043eba9b36c9672c18a8d6896b9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636575732d6d656469612f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ceus-media/database)[![Package version](https://camo.githubusercontent.com/85b468db4cdbb1b2fe82128dfa33fe3ad5707170d96950485cdc7e33f0c73a3f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636575732d6d656469612f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ceus-media/database)[![License](https://camo.githubusercontent.com/d639cdf74cbef2e5dfec4e07d40db7ef0111fd88424606a4587f9fa007ac30e8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636575732d6d656469612f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ceus-media/database)

PHP database access

Installation
------------

[](#installation)

### Composer

[](#composer)

Install this library using composer:

```
composer require ceus-media/Database

```

Within your code, load library:

```
require_once 'vendor/autoload.php';
```

Code Examples using PDO
-----------------------

[](#code-examples-using-pdo)

### Database Connection

[](#database-connection)

```
$dbDriver	= 'mysql';
$dbName		= 'myDatabase';
$dbUsername	= 'myDatabaseUser';
$dbPassword	= 'myDatabasePassword';

$dbc	= new \CeusMedia\Database\PDO\Connection(
	new \CeusMedia\Database\PDO\DataSourceName( $dbDriver, $dbName ),
	$dbUsername, $dbPassword
);
```

### Tables

[](#tables)

Existing database tables can be declared as tables:

#### Table class

[](#table-class)

```
class MyFirstTable extends \CeusMedia\Database\PDO\Table
{
	protected string $name			= "my_first_table";
	protected array $columns		= [
		'id',
		'maybeSomeForeignId',
		'content',
	];
	protected string $primaryKey	= 'id';
	protected array $indices		= [
		'maybeSomeForeignId',
	];
	protected int $fetchMode		= \PDO::FETCH_OBJ;
}
```

#### Table instance

[](#table-instance)

Having this defined structure, you can use a table instance for reading from and writing into the database table. Hence that you need to create a database connection beforehand.

```
$table	= new MyFirstTable( $dbc );
```

#### Reading an entry

[](#reading-an-entry)

Example for getting an entry by its primary key:

```
$entry	= $table->get( 1 );
```

The result will be an object of table columns and their values, since the fetch mode is set to object-wise by table structure:

```
object stdObject(
    'id'                 => 1,
    'maybeSomeForeignId' => 123,
    'content'            => 'Content of first entry.'
)
```

Not having the fetch mode set would result in an associated array, which is set as default fetch mode in underlaying table reader. To change the fetch see below.

**Hint:** There are more methods to read a single entry:

- getByIndex
- getByIndices

which allow to focus on foreign indices instead of the primary key.

#### Finding entries

[](#finding-entries)

A group of entries, filtered by a foreign key:

```
$someEntries	= $table->getAllByIndex( 'maybeSomeForeignId', 123 );
```

A group of entries, filtered by several foreign keys:

```
$indices = [
    'maybeSomeForeignId' => 123,
    'notExistingKey'     => 'will result in an exception',
];
$someEntries	= $table->getAllByIndices( $indices );
```

To get **all entries**, call:

```
$allEntries	= $table->getAll();
```

which may be bad in scaling, so reduce the result set by defining limits and conditions:

```
$conditions = ['content' => '%test%'];
$orders     = [];
$limits     = [$offset = 0, $limit = 10];

$allEntries = $table->getAll( $conditions, $orders, $limits );
```

Conditions can be indices or any other column.

Orders are pairs of columns and directions, like:

```
$orders	= [
    'maybeSomeForeignId' => 'DESC',
    'content'            => 'ASC',
];
```

There are more parameters possible for each of this indexing methods, which allow:

- fields: restricting columns in result set
- grouping: apply GROUP BY
- having: apply HAVING

#### Counting

[](#counting)

To count entries by a foreign key:

```
$number	= $table->countByIndex( 'maybeSomeForeignId', 123 );
```

To count entries, filtered by several foreign keys:

```
$number = $table->countByIndices( [
    'maybeSomeForeignId' => 123,
    'notExistingKey'     => 'will result in an exception',
] );
```

To get **all entries**, call:

```
$number	= $table->count();
```

which may be bad in scaling, so reduce the result set by defining conditions:

```
$Conditions	= [
    'maybeSomeForeignId' => 123,
    'content'            => '%test%',
];
$number	= $table->count( $conditions );
```

**Hint:** Counting having really large MySQL tables may be slow. There is a method to count in large tables in a faster way. You will find it.

#### Adding an entry

[](#adding-an-entry)

```
$data = [
    'maybeSomeForeignId' => 123,
    'content'            => 'Second entry.',
];
$entryId	= $table->add( $data );
```

**Attention:** For security reasons, all HTML tags will be striped. Set second parameter to FALSE to avoid that, if needed. Make sure to strip HTML tags of none-HTML columns manually!

#### Updating an entry

[](#updating-an-entry)

```
$primaryKey = 2;
$data       = [
    'maybeSomeForeignId' => 124,
    'content'            => 'Second entry - changed.',
];
$result	= $table->edit( $primaryKey, $data );
```

where the result will be the number of changed entries.

**Attention:** For security reasons, all HTML tags will be striped. Set third parameter to FALSE to avoid that, if needed. Make sure to strip HTML tags of none-HTML columns manually!

#### Updating several entries

[](#updating-several-entries)

```
$indices = [
    'maybeSomeForeignId' => 123,
];
$data    = [
    'maybeSomeForeignId' => 124,
];
$result  = $table->editByIndices( $indices, $data );
```

where the result will be the number of changed entries.

**Attention:** For security reasons, all HTML tags will be striped. Set third parameter to FALSE to avoid that, if needed. Make sure to strip HTML tags of none-HTML columns manually!

#### Removing an entry

[](#removing-an-entry)

```
$primaryKey = 2;
$result     = $table->remove( $primaryKey );
```

where the result will be the number of removed entries.

#### Removing several entry

[](#removing-several-entry)

```
$indices = [
    'maybeSomeForeignId' => 123,
];
$result  = $table->removeByIndices( $indices );
```

where the result will be the number of removed entries.

#### Change fetch mode

[](#change-fetch-mode)

In your table structure class, set:

```
    protected int $fetchMode = \PDO::[YOUR_FETCH_MODE];
```

where YOUR\_FETCH\_MODE is one of these standard PDO fetch modes:

- FETCH\_ASSOC
- FETCH\_NAMED
- FETCH\_NUM
- FETCH\_BOTH
- FETCH\_OBJ

### Entities

[](#entities)

Reading from tables can return lists of arrays or anonymous objects, easily.
To use entity classes to receive data objects, PDO's fetch mode can be set to `FETCH_CLASS`. A table implementation needs to set `::fetchEntityClass` to a class name.

This could be an entity class:

```
class MyFirstTableEntity
{
    public string $id;
    public string $maybeSomeForeignId;
    public string $content;
}

```

This entity class can be linked within the table as class to use on fetch:

```
class MyFirstTable extends Table
{
    ...
    public ?string $fetchEntityClass = '\\MyProject\\MyFirstTableEntity';
}

```

Now, all indexing methods will return lists of filled entity classes.

Code Examples using OSQL
------------------------

[](#code-examples-using-osql)

Having a config file like this:

```
driver   = 'mysql';
host     = 'myHost';
port     = 'myPort';
database = 'myDatabase';
username = 'myDatabaseUser';
password = 'myDatabasePassword';
```

and assuming that you load things up like this:

```
require_once 'vendor/autoload.php';

use CeusMedia\Database\PDO\DataSourceName;
use CeusMedia\Database\OSQL\Client;
use CeusMedia\Database\OSQL\Connection;
use CeusMedia\Database\OSQL\Condition;
use CeusMedia\Database\OSQL\Table;
use CeusMedia\Database\OSQL\Query\Select;

$config	= (object) parse_ini_file( 'myConfigFile.ini' );
```

you can connect to a database like this:

```
$client	= new Client( new Connection( DataSourceName::renderStatic(
    $config->driver,
    $config->database,
    $config->host,
    $config->port,
    $config->username,
    $config->password
), $config->username, $config->password ) );
```

Now you can query the database like this:

```
$result	= Select::create( $client )
    ->from( new Table( 'galleries', 'g' ) )
    ->where( new Condition( 'galleryId', 1, Condition::OP_EQ ) )
    ->execute();
```

The result will contain the requested rows (only one in this example):

```
new UI_DevOutput();
print_m( $result );
```

will produce:

```
[O] 0 -> stdClass
   [S] galleryId => 1
   [S] status => 0
   [S] rank => 1
   [S] path => test
   [S] title => Test
   [S] description => Das ist ein Test.
   [S] timestamp => 1402008611
```

###  Health Score

54

—

FairBetter than 96% of packages

Maintenance92

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 98.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.

###  Release Activity

Cadence

Every ~180 days

Recently: every ~40 days

Total

23

Last Release

33d ago

PHP version history (7 changes)0.1PHP &gt;=5.3.0

0.3PHP ^5.3 | ^7

0.4.0PHP ~7.2

0.4.4PHP &gt;=7.2

0.5.0PHP ^7.4 | ^8

0.6.0PHP ^8.1

0.7.0PHP ^8.3

### Community

Maintainers

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

---

Top Contributors

[![kriss0r](https://avatars.githubusercontent.com/u/476914?v=4)](https://github.com/kriss0r "kriss0r (174 commits)")[![cwuerker-c24](https://avatars.githubusercontent.com/u/155151774?v=4)](https://github.com/cwuerker-c24 "cwuerker-c24 (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ceus-media-database/health.svg)

```
[![Health](https://phpackages.com/badges/ceus-media-database/health.svg)](https://phpackages.com/packages/ceus-media-database)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[pgvector/pgvector

pgvector support for PHP

198741.5k12](/packages/pgvector-pgvector)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

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