-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.php
106 lines (95 loc) · 3.16 KB
/
db.php
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
101
102
103
104
105
106
<?php
class db
{
protected $pdo;
private $server;
private $db;
private $user;
private $password;
private $tbl;
public function __construct($server = "", $db = "", $user = "", $pass = "")
{
$this->server = $server;
$this->db = $db;
$this->user = $user;
$this->password = $pass;
$this->connection();
}
public function connection()
{
try {
$this->pdo = new PDO("mysql:host={$this->server};dbname={$this->db}", $this->user, $this->password);
} catch (Exception $e) {
die($e->getMessage());
}
}
//set table's name from front
public function setTbl($tbl)
{
$this->tbl = $tbl;
}
//general select data
public function selectData($data)
{
if (is_array($data)) {
//generate sql command. change arry(? , ? , ?) to '?' , '?' , '?'.
$value = "'" . implode("','", $data) . "'";
} else {
$value = "'" . $data . "'";
}
$stm = $this->pdo->prepare("SELECT {$value} FROM {$this->tbl}");
$stm->execute();
$row = $stm->fetchAll(PDO::FETCH_OBJ);
return $row;
}
//general insert to database
public function insertData($fields, $data)
{
if (is_array($data)) {
//generate sql command
$data = "'" . implode("','", $data) . "'";
$fields = implode(",", $fields);
}
$stm = $this->pdo->prepare("INSERT INTO {$this->tbl} ($fields) VALUES ($data)");
$stm->execute();
}
//general update a record from database (email is unique in this database.)
public function updateData($id, $fields, $data)
{
//we need change many filds
if (is_array($fields)) {
foreach ($fields as $key => $val) {
$command [] = $val . "='" . $data[$key] . "'";
}
$command = implode(",", $command);
} else {
//or just we need change one field
$command = "'{$fields}'='{$data}'";
}
$stm = $this->pdo->prepare("UPDATE {$this->tbl} SET " . $command . " WHERE id='$id'");
$stm->execute();
}
//general delete a record from database (email is unique in this database.)
public function deleteData($id)
{
$stm = $this->pdo->prepare("DELETE FROM {$this->tbl} WHERE id='$id'");
$stm->execute();
}
//general search for data from database
public function searchData($key, $value)
{
$stm = $this->pdo->prepare("SELECT * FROM {$this->tbl} WHERE $key='$value'");
$stm->execute();
//we assume one field from the table is unique then return just one record
$results = $stm->fetch(PDO::FETCH_OBJ);
return $results;
}
//general search for data from the database
public function searchLikeData($key, $value)
{
$stm = $this->pdo->prepare("SELECT * FROM {$this->tbl} WHERE $key LIKE '$value'");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_OBJ);
return $results;
}
}