Инструменты пользователя

Инструменты сайта


works:programmer:php:pdo-wrapper

Врапер PDO для PHP

Код класса

PDOwrap.php
<?PHP
 
class PDOwrap extends PDO
{
 
    public function fetchAll($SQL, $input_parameters=NULL)
    {
        if (false === ($stmt = $this->prepare($SQL))) return NULL;
        if (!$stmt->execute($input_parameters)) return NULL;
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
 
    public function fetchRow($SQL, $input_parameters=NULL)
    {
        if (false === ($stmt = $this->prepare($SQL))) return NULL;
        if (!$stmt->execute($input_parameters)) return NULL;
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
 
    public function fetchScalar($SQL, $input_parameters=NULL, $column_number=NULL)
    {
        if (false === ($stmt = $this->prepare($SQL))) return NULL;
        if (!$stmt->execute($input_parameters)) return NULL;
        $result = [];
        while (false !== ($colmn = $stmt->fetchColumn($column_number))) $result[] = $colmn;
        return $result;
    }
 
    public function exec2($SQL, $input_parameters)
    {
        if (false === ($stmt = $this->prepare($SQL))) return NULL;
        if (!$stmt->execute($input_parameters)) return NULL;
        return TRUE;
    }
 
}

Пример использования

usage.php
<?PHP
require_once('PDOwrap.php');
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Content-Type: text/plain');
$dbw = new PDOwrap('sqlite::memory:');
print_r($dbw->fetchAll('SELECT ? as a, 2 as b, 3 as c UNION SELECT ?, DATE(\'now\'), TIME(\'now\') UNION SELECT ?, 8, 9', [23, 12, 22]));
 
$SQL = <<< 'END_SQL'
CREATE TABLE [users] (
    [login] TEXT NOT NULL,
    [paswd] TEXT,
    [autht] TEXT,
    [email] TEXT,
    [created] TEXT NOT NULL,
    [logined] TEXT,
    [deleted] TEXT
)
END_SQL;
 
$dbw->exec($SQL);
$dbw->exec('CREATE INDEX [idx_user_auth] ON [users] ([login], [paswd])');
$dbw->exec('INSERT INTO [users] ([login], [paswd], [created], [deleted]) VALUES (\'admin\', \'\', DATETIME(\'now\'), DATETIME(\'now\'))');
 
$dbw->exec2('INSERT INTO [users] ([login], [paswd], [created]) VALUES (?, ?, DATETIME(\'now\'))', ['User1', md5('password')]);
 
$SQL = 'INSERT INTO [users] ([login], [paswd], [created]) VALUES (:user, :pass, DATETIME("now"))';
$dbw->exec2($SQL, [
    'user' => 'User2', 
    'pass' => md5('password2')
]);
 
var_dump($dbw->lastInsertId());
 
print_r($dbw->fetchAll('SELECT [login], [created], [logined] FROM [users] WHERE [deleted] IS NULL'));
works/programmer/php/pdo-wrapper.txt · Последнее изменение: 2024/07/17 03:41 — 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki