PHP code example of onebytesolutions / database

1. Go to this page and download the library: Download onebytesolutions/database library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

onebytesolutions / database example snippets


composer 

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();
}

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

// example of inserting a bunch of rows
$rows = [];
$rows[] = [
        'name' => 'John Doe ',
        'email' => '[email protected]'
];
$rows[] = [
        'name' => 'Jane Doe ',
        'email' => '[email protected]'
];
$rows[] = [
        'name' => 'Sarah Doe ',
        'email' => '[email protected]'
];
$database->insertRowBatch("users", $rows);

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

// 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>';

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

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