Skip to content

onebytesolutions/database

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Database Library - A dependency injection based Database Class


### Table of Contents

Installation
Initialization
Insert Query
Insert Batch Query
Update Query
Select Query
Delete Query
Raw Query

About

This software was developed during my free time and is free to use.

Installation

Composer

composer require onebytesolutions/database

Initialization

Simple initialization:

use OneByteSolutions\Database\Database,
    OneByteSolutions\Database\Adapters\PdoAdapter;

// set db config
$db = [
    'host' => 'localhost',
    'user' => 'db-username',
    'pass' => 'db-password',
    'database' => 'database-name'
	// OPTIONAL: ,'port' => 3308 
];

// try to connect to the database
try {
    $database = new Database(new PdoAdapter($db));
    $database->connect();
}catch (\Exception $e){
    echo "Unable to connect: ".$e->getMessage();
}

Insert Query

Simple example

// example of inserting a new user, with transactions
$database->beginTransaction();
try {
    $row = [
        'name' => 'John Doe',
        'email' => 'john.doe@example.org'
    ];
    $id = $database->insertRow("users", $row);
    $database->commit();
    
    echo 'inserted id: '.$id;
} catch(\Exception $e){
    echo 'insert failure';
    $database->rollBack();
}

Insert Batch Query

Simple example

// example of inserting a bunch of rows
$rows = [];
$rows[] = [
        'name' => 'John Doe ',
        'email' => 'john.doe@example.org'
];
$rows[] = [
        'name' => 'Jane Doe ',
        'email' => 'jane.doe@example.org'
];
$rows[] = [
        'name' => 'Sarah Doe ',
        'email' => 'sarah.doe@example.org'
];
$database->insertRowBatch("users", $rows);

Update Query

// example of updating a row
$database->updateRowWhere("user", ["lastLogin" => time()], "id", 1);

Select Query

// example of fetching a query as an array
$sql = "SELECT * FROM users LIMIT 30";
$params = [];
$results = $database->queryToArray($sql, $params);

echo '<pre>'.print_r($results,true).'</pre>';

Delete Query

// example of deleting a row
$database->deleteWhere("users", "id", 1);

Raw Query

// example of running raw sql
$database->run("UPDATE users SET name = :name", ['name' => 'Alex Doe']);

About

A simple drop-in PHP database library

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages