1. Go to this page and download the library: Download delight-im/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/ */
delight-im / db example snippets
$dataSource = new \Delight\Db\PdoDataSource('mysql'); // see "Available drivers for database systems" below
$dataSource->setHostname('localhost');
$dataSource->setPort(3306);
$dataSource->setDatabaseName('my-database');
$dataSource->setCharset('utf8mb4');
$dataSource->setUsername('my-username');
$dataSource->setPassword('my-password');
$db = \Delight\Db\PdoDatabase::fromDataSource($dataSource);
$db = \Delight\Db\PdoDatabase::fromDsn(
new \Delight\Db\PdoDsn(
'mysql:dbname=my-database;host=localhost',
'my-username',
'my-password'
)
);
// $pdo = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
$db = \Delight\Db\PdoDatabase::fromPdo($pdo);
$rows = $db->select('SELECT id, name FROM books');
// or
$rows = $db->select(
'SELECT name, year FROM books WHERE author = ? ORDER BY copies DESC LIMIT 0, 10',
[ 'Charles Dickens' ]
);
// or
$row = $db->selectRow(
'SELECT author, year FROM books WHERE author <> ? ORDER BY year ASC LIMIT 0, 1',
[ 'Miguel de Cervantes' ]
);
// or
$value = $db->selectValue(
'SELECT year FROM books WHERE name <> ? AND name <> ? ORDER BY year DESC LIMIT 0, 1',
[
'Tale of Two Cities',
'Alice in Wonderland'
]
);
// or
$column = $db->selectColumn(
'SELECT author FROM books ORDER BY copies DESC LIMIT ?, ?',
[
0,
3
]
);
$db->insert(
'books',
[
// set
'name' => 'Don Quixote',
'author' => 'Miguel de Cervantes',
'year' => 1612
]
);
$newId = $db->getLastInsertId();
// or
$newId = $db->getLastInsertId('my-sequence-name');
$db->update(
'books',
[
// set
'author' => 'J. K. Rowling',
'copies' => 2
],
[
// where
'name' => "Harry Potter and the Philosopher's Stone"
]
);
$db->delete(
'books',
[
// where
'author' => 'C. S. Lewis',
'year' => 1949
]
);
$db->exec(
'INSERT INTO books (name, author, year) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE copies = copies + 1',
[
"Harry Potter and the Philosopher's Stone",
'J. K. Rowling',
1997
]
);
// or
$db->exec(
"UPDATE books SET name = CONCAT(LEFT(name, 5), ' in ', RIGHT(name, 10)) WHERE year >= ? AND year < ?",
[
1860,
1890
]
);
$db->beginTransaction();
// and later
$db->commit();
// or
$db->rollBack();
// and optionally
$active = $db->isTransactionActive();