PHP code example of xrstf / comfydb

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

    

xrstf / comfydb example snippets


use xrstf\ComfyDB;

$db = ComfyDB::connect('host', 'user', 'password', 'database');

// alternatively, wrap an existing mysqli connection
$db = new ComfyDB($mysqliConnection);

$rows = $db->query('SELECT id, firstname, lastname FROM persons');

/*
$rows = [
    ['id' => 1, 'firstname' => 'Tom', 'lastname', 'Schlock'],
    ['id' => 2, 'firstname' => 'Max', 'lastname', 'Power'],
    ['id' => 3, 'firstname' => 'Maria', 'lastname', 'Gomez'],
    ...
];
*/

// use %s for strings, %d for integers, %f for floats and %n for NULLable values
// (%n will result in 'NULL' if the given value is null, otherwise it will encode
// the value as a string, like %s)
$rows = $db->query('SELECT * FROM persons WHERE firstname = %s AND id = %d', ['Tom', 1]);

$names = $db->fetchColumn('SELECT firstname FROM persons WHERE 1');
// $names = ['Max', 'Tom', 'Maria'];

// select three columns, use ID as the key
$names = $db->fetchMap('SELECT id, firstname, lastname FROM persons WHERE 1');

/*
$names = [
    1 => ['firstname' => 'Tom', 'lastname', 'Schlock'],
    2 => ['firstname' => 'Max', 'lastname', 'Power'],
    3 => ['firstname' => 'Maria', 'lastname', 'Gomez'],
];
*/

// select two columns
$names = $db->fetchMap('SELECT id, firstname FROM persons WHERE 1');

/*
$names = [
    1 => 'Tom',
    2 => 'Max',
    3 => 'Maria',
];
*/

// fetch a single cell from the database
$firstname = $db->fetch('SELECT firstname FROM persons WHERE id = %d', [1]);
// $firstname = 'Tom'

// fetch more than one cell
$name = $db->fetch('SELECT firstname, lastname FROM persons WHERE id = %d', [1]);
// $name = ['firstname' => 'Tom', 'lastname', 'Schlock']

// find no rows (returns always null, disregarding of the number of columns selected)
$row = $db->fetch('SELECT * FROM table WHERE 1 = 2');
// $row = null

$newData = [
    'firstname' => 'Anja',
    'lastname' => 'Muster',
];

// for simple conditions, you can give the WHERE criteria as an array
$db->update('persons', $newData, ['id' => 3]);

// more complex criteria can be given as a string, which is copied verbatim
$db->update('persons', $newData, '(firstname NOT NULL OR lastname NOT LIKE "%foo")');

$newData = [
    'firstname' => 'Anja',
    'lastname' => 'Muster',
];

$db->insert('persons', $newData);

$id = $db->getInsertedID();

$db->delete('persons', ['id' => 2]);
$deleted = $db->getAffectedRows();

try {
    $db->delete('nope', ['id' => 2]);
}
catch (ComfyException $e) {
    print "Query: ".$e->getQuery()."\n";
    print "Code : ".$e->getCode()."\n";
    print "Error: ".$e->getErrorMessage()."\n";
}