-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.php
More file actions
100 lines (81 loc) · 2.81 KB
/
common.php
File metadata and controls
100 lines (81 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
// Common.php - Database connection helper & common function
class Database {
private static $instance = null;
private $pdo;
private function __construct($config) {
try {
$dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
$this->pdo = new PDO(
$dsn,
$config['username'],
$config['password'],
$config['options']
);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
public static function getInstance($config = null) {
if (self::$instance === null) {
if ($config === null) {
// Load config automatically
$config = require __DIR__ . '/config.php';
$config = $config['database'];
}
self::$instance = new self($config);
}
return self::$instance;
}
public function getConnection() {
return $this->pdo;
}
// Helper methods for common operations
public function query($sql, $params = []) {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
public function fetch($sql, $params = []) {
return $this->query($sql, $params)->fetch();
}
public function fetchAll($sql, $params = []) {
return $this->query($sql, $params)->fetchAll();
}
public function insert($table, $data) {
$columns = implode(', ', array_keys($data));
$placeholders = ':' . implode(', :', array_keys($data));
$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
return $this->pdo->lastInsertId();
}
public function update($table, $data, $where, $whereParams = []) {
$set = [];
foreach ($data as $key => $value) {
$set[] = "{$key} = :{$key}";
}
$setClause = implode(', ', $set);
$sql = "UPDATE {$table} SET {$setClause} WHERE {$where}";
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array_merge($data, $whereParams));
return $stmt->rowCount();
}
}
function wkSign($to_sign, $api_secret_key) {
$error = "";
try {
if (!($privateKeyResource = openssl_pkey_get_private($api_secret_key))) {
throw new Exception("Could not load private key");
}
if (!openssl_sign($to_sign, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256)) {
throw new Exception("Signature generation failed");
}
} catch(Exception $e) {
$error = $e->getMessage();
}
if ($error) {
return ["error" => $error];
}
return ["signature" => bin2hex($signature)];
}