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

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

ideaglory/database
==================

PHP Singleton Database Class

v1.0.0(1y ago)03MITPHP

Since Dec 23Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ideaglory/database)[ Packagist](https://packagist.org/packages/ideaglory/database)[ Docs](https://ideaglory.com)[ RSS](/packages/ideaglory-database/feed)WikiDiscussions main Synced 1mo ago

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

PHP Singleton Database Class
============================

[](#php-singleton-database-class)

A lightweight and reusable PHP class to manage database connections using the Singleton pattern. This class ensures only one database connection instance exists during the runtime, providing an efficient and easy-to-use database interface.

Features
--------

[](#features)

- Singleton pattern to prevent multiple connections.
- Parameterized query support to prevent SQL injection.
- Basic transaction management (`beginTransaction`, `commit`, `rollback`).
- Utility methods for fetching data (`fetchAll`, `fetchOne`).
- Supports prepared statements with bound parameters.
- Auto-close connection and reset instance when closed.

---

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

[](#installation)

You can install this package via [Composer](https://getcomposer.org/). Run the following command:

```
composer require ideaglory/database
```

---

Usage
-----

[](#usage)

### Basic Initialization

[](#basic-initialization)

The `Database` class uses the Singleton pattern. To initialize it:

```
use Ideaglory\Database;

$db = Database::getInstance('host', 'username', 'password', 'database', 'charset');
```

### Querying the Database

[](#querying-the-database)

#### Execute a Query

[](#execute-a-query)

To execute a query with parameters:

```
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$params = ['John Doe', 'john.doe@example.com'];
$db->query($sql, $params);
```

#### Fetch All Rows

[](#fetch-all-rows)

```
$sql = "SELECT * FROM users WHERE status = ?";
$params = ['active'];
$users = $db->fetchAll($sql, $params);
print_r($users);
```

#### Fetch a Single Row

[](#fetch-a-single-row)

```
$sql = "SELECT * FROM users WHERE id = ?";
$params = [1];
$user = $db->fetchOne($sql, $params);
print_r($user);
```

### Transactions

[](#transactions)

#### Begin a Transaction

[](#begin-a-transaction)

```
$db->beginTransaction();
```

#### Commit a Transaction

[](#commit-a-transaction)

```
$db->commit();
```

#### Rollback a Transaction

[](#rollback-a-transaction)

```
$db->rollback();
```

### Close Connection

[](#close-connection)

When the database connection is no longer needed:

```
$db->close();
```

---

Use Cases
---------

[](#use-cases)

1. **Efficient Database Management**: Ensures only one instance of the database connection exists during runtime, improving resource utilization.
2. **Simplified Query Execution**: Provides easy-to-use methods for executing queries and fetching results.
3. **Secure Applications**: Prevents SQL injection with parameterized queries.
4. **Transaction Support**: Handles database transactions for complex operations.

---

Example
-------

[](#example)

Below is a complete example demonstrating various features:

```
use Ideaglory\Database;

try {
    $db = Database::getInstance('localhost', 'root', '', 'example_db', 'utf8mb4');

    // Insert a new user
    $db->query("INSERT INTO users (name, email) VALUES (?, ?)", ['Alice', 'alice@example.com']);

    // Fetch all active users
    $users = $db->fetchAll("SELECT * FROM users WHERE status = ?", ['active']);
    print_r($users);

    // Start a transaction
    $db->beginTransaction();

    // Update a user
    $db->query("UPDATE users SET email = ? WHERE id = ?", ['alice.new@example.com', 1]);

    // Commit the transaction
    $db->commit();

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
    $db->rollback(); // Rollback if an error occurs
} finally {
    $db->close(); // Close the connection
}
```

---

Contributing
------------

[](#contributing)

Feel free to fork this repository and submit pull requests for improvements or bug fixes.

License
-------

[](#license)

This project is licensed under the MIT License. See the LICENSE file for details.

Author
------

[](#author)

Created by [IdeaGlory](https://ideaglory.com).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance40

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

511d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/94f498f22eec76001b6ca6757c9b8fcc17a9d94dabe9cd297d5d5efd4766c270?d=identicon)[ideaglory](/maintainers/ideaglory)

---

Top Contributors

[![ideaglory](https://avatars.githubusercontent.com/u/161056510?v=4)](https://github.com/ideaglory "ideaglory (3 commits)")

---

Tags

phpdatabasemysqlsingletonideaglory

### Embed Badge

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

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

###  Alternatives

[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)[stefangabos/zebra_database

An advanced, compact and lightweight MySQL database wrapper library, built around PHP's MySQLi extension.

11812.0k](/packages/stefangabos-zebra-database)[popphp/pop-db

Pop Db Component for Pop PHP Framework

1814.6k11](/packages/popphp-pop-db)[riverside/php-orm

PHP ORM micro-library and query builder

111.2k](/packages/riverside-php-orm)

PHPackages © 2026

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