You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.6 KiB
87 lines
2.6 KiB
<?php
|
|
|
|
namespace app\common\dm;
|
|
|
|
class DmDB {
|
|
private $host;
|
|
private $port;
|
|
private $dbname;
|
|
private $username;
|
|
private $password;
|
|
private $conn;
|
|
|
|
public function __construct($host, $port, $dbname, $username, $password) {
|
|
$this->host = $host;
|
|
$this->port = $port;
|
|
$this->dbname = $dbname;
|
|
$this->username = $username;
|
|
$this->password = $password;
|
|
$this->connect();
|
|
}
|
|
|
|
private function connect() {
|
|
$dsn = "dm:host=$this->host;port=$this->port;dbname=$this->dbname";
|
|
try {
|
|
$this->conn = new \PDO($dsn, $this->username, $this->password);
|
|
$this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
|
} catch (\PDOException $e) {
|
|
echo "Connection failed: " . $e->getMessage();
|
|
die();
|
|
}
|
|
}
|
|
|
|
public function execute($sql, $params = array()) {
|
|
try {
|
|
$stmt = $this->conn->prepare($sql);
|
|
foreach ($params as $key => &$value) {
|
|
$stmt->bindParam($key, $value);
|
|
}
|
|
$stmt->execute();
|
|
return $stmt;
|
|
} catch (\PDOException $e) {
|
|
echo "Execution failed: " . $e->getMessage();
|
|
die();
|
|
}
|
|
}
|
|
|
|
public function insert($table, $data) {
|
|
$fields = implode(', ', array_keys($data));
|
|
$values = implode(', ', array_fill(0, count($data), '?'));
|
|
$sql = "INSERT INTO $table ($fields) VALUES ($values)";
|
|
$params = array_values($data);
|
|
return $this->execute($sql, $params);
|
|
}
|
|
|
|
public function select($table, $where = '', $params = array()) {
|
|
$sql = "SELECT * FROM $table";
|
|
if (!empty($where)) {
|
|
$sql .= " WHERE $where";
|
|
}
|
|
return $this->execute($sql, $params)->fetchAll(\PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
public function update($table, $data, $where = '', $params = array()) {
|
|
$sets = array();
|
|
foreach ($data as $key => $value) {
|
|
$sets[] = "$key = ?";
|
|
}
|
|
$sql = "UPDATE $table SET " . implode(', ', $sets);
|
|
if (!empty($where)) {
|
|
$sql .= " WHERE $where";
|
|
}
|
|
$params = array_merge(array_values($data), $params);
|
|
return $this->execute($sql, $params);
|
|
}
|
|
|
|
public function delete($table, $where = '', $params = array()) {
|
|
$sql = "DELETE FROM $table";
|
|
if (!empty($where)) {
|
|
$sql .= " WHERE $where";
|
|
}
|
|
return $this->execute($sql, $params);
|
|
}
|
|
|
|
public function lastInsertId() {
|
|
return $this->conn->lastInsertId();
|
|
}
|
|
}
|