PHP code example of hengeb / db

1. Go to this page and download the library: Download hengeb/db 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/ */

    

hengeb / db example snippets




use Hengeb\Db\Db;

$db = new Db([
    "host" => "example.org",
    "port" => 3306,
    "database" => "my_database",
    "user" => "johndoe",
    "password" => "secret"
]);

// alternative:
$db = Db::getInstance();
/**
 * in this case the configuration will be loaded from environment variables
 * - MYSQL_HOST (default: localhost)
 * - MYSQL_PORT (default: 3306)
 * - MYSQL_DATABASE (default: database)
 * - MYSQL_USER (no default, allNames = $db->query("SELECT name FROM contacts ORDER BY name")->getColumn();
// $allNames === ["Alice", "Bob", "Jane", "Joe"]

// get single row
$contact = $db->query("SELECT name, phone FROM contacts WHERE id=:id", ["id" => $id])->getRow();
// $contact === ["name" => "Jane", "phone" => "555-123"]

// get associative array with the datra
$contacts = $db->query("SELECT name, phone FROM contacts ORDER BY name")->getAll();
// $contacts === [["name" => "Alice", "phone" => "555-987"], ...]

// reuse prepared statement
$names = [];
$statement = $db->prepare("SELECT name FROM contacts WHERE id=:id");
for ([1, 2, 3, 4] as $id) {
    $names[] = $statement->bind(["id" => $id])->execute()->get();
}
// $names === ["Bob", "Alice", "Joe", "Jane"]

// transaction:
$db->beginTransaction();
$db->query("INSERT INTO contacts SET name=:name, phone=:phone", [
    "name" => "Claire",
    "phone" => "555-222",
]);
$db->commit(); // or $db->rollback()