PHP code example of jtrw / dao
1. Go to this page and download the library: Download jtrw/dao 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/ */
jtrw / dao example snippets
$db = new PDO(
$GLOBALS['config']['db']['dsn'],
$GLOBALS['config']['db']['user'],
$GLOBALS['config']['db']['pass']
);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
$res = $db->query('SET NAMES utf8mb4');
if (!$res) {
throw new Exception('Database connection error');
}
$db = DataAccessObject::factory($db);
// Insert single record
$id = $db->insert('users', [
'name' => 'John Doe',
'email' => '[email protected] '
]);
// Insert with duplicate key update
$id = $db->insert('users', [
'name' => 'John Doe',
'email' => '[email protected] '
], true);
// Update records
$db->update('users',
['name' => 'Jane Doe'],
['id' => 1]
);
// Delete records
$db->delete('users', ['id' => 1]);
// Insert multiple records
$data = [
['name' => 'User 1', 'email' => '[email protected] '],
['name' => 'User 2', 'email' => '[email protected] ']
];
$db->massInsert('users', $data);
$search = [
'columnName' => 5,
'columnName2&IN' => [1, 2, 3, 4]
'columnName3&<' => 7,
'columnName4&>=' => 3
];
$sql = "SELECT * FROM users";
$result = $db->select($sql, $search, [], DataAccessObjectInterface::FETCH_ALL);
$data = $result->toNative(); // Convert to native PHP array
// Manual transaction handling
$db->begin();
try {
$db->insert('users', ['name' => 'John']);
$db->insert('orders', ['user_id' => $db->getInsertID(), 'total' => 100]);
$db->commit();
} catch (Exception $e) {
$db->rollback();
throw $e;
}
// Get tables list
$tables = $db->getTables();
// Quote table/column names
$quotedTable = $db->quoteTableName('user_data');
$quotedColumn = $db->quoteColumnName('user-name');
// Get database type
$dbType = $db->getDatabaseType(); // mysql, pgsql, etc.
// Check transaction status
if ($db->inTransaction()) {
// Inside transaction
}
// Ensure proper PDO configuration
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
]);