test-php-rest-api-user/engine/class/0001.db.php

61 lines
1.3 KiB
PHP
Raw Normal View History

2024-08-10 00:30:13 +08:00
<?php
class DB {
private static $pdos = [];
public static function init($conf = []) {
try {
foreach($conf as $title => $data) {
$dsn = sprintf('%s:dbname=%s;host=%s;port=%d;charset=%s',
$data['driver'],
$data['name'],
$data['host'],
$data['port'],
$data['charset']
);
self::$pdos[$title] = new PDO($dsn, $data['user'], $data['password'], $data['options']);
}
return true;
}
catch(\Throwable $th) {
return false;
}
}
public static function getQuery($db, $sql, $args = null) {
if(!is_array($args) && !empty($args))
$args = [$args];
$stmt = self::$pdos[$db]->prepare($sql);
try {
$stmt->execute($args);
}
catch(\Throwable $th) {
Debug::print($sql);
Debug::print($args);
Debug::print($th);
}
if(stristr($sql, 'SELECT'))
return $stmt->fetch(PDO::FETCH_OBJ);
if(stristr($sql, 'INSERT'))
return self::$pdos[$db]->lastInsertId();
return true;
}
public static function getQueryAll($db, $sql, $args = null) {
if(!is_array($args) && !empty($args))
$args = [$args];
$stmt = self::$pdos[$db]->prepare($sql);
$stmt->execute($args);
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
}
if(!DB::init($config['db'])) {
die('DB not connected! Recheck configs!');
}