-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTable.php
66 lines (66 loc) · 2.12 KB
/
Table.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
<?php
namespace Web4cstj\DB;
use PDO;
class Table
{
static protected $database = Database::class;
static protected $table = null;
static protected $champs = [];
static public function connect(){
return static::$database::connect();
}
static public function all($champs = '*', $order = '')
{
$pdo = static::connect();
if (is_array($champs)) {
$champs = implode(',', $champs);
}
if ($order) {
$order = " ORDER BY $order";
}
$sql = "SELECT {$champs} FROM " . static::$table . "$order";
$stmt = $pdo->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_CLASS, static::class);
$stmt->execute();
$resultat = $stmt->fetchAll();
return $resultat;
}
static public function find($id)
{
$pdo = static::connect();
$stmt = $pdo->prepare("SELECT * FROM " . static::$table . " WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->setFetchMode(PDO::FETCH_CLASS, static::class);
$stmt->execute();
$resultat = $stmt->fetch();
return $resultat;
}
public function save() {
$pdo = static::connect();
if ($this->id) {
$set = [];
foreach (static::$champs as $champ => $etiquette) {
$set = "$champ=>$champ";
}
$set = "SET ".implode(', ', $set);
$stmt = $pdo->prepare("UPDATE " . static::$table . " $set WHERE id=:id");
$this->bind($stmt, 'id');
} else {
$champs = implode(', ', array_keys(static::$champs));
$values = ':'. implode(', :', array_keys(static::$champs));
$stmt = $pdo->prepare("INSERT INTO " . static::$table . " ($champs) VALUES ($values)");
}
$this->bind($stmt, array_keys(static::$champs));
$stmt->execute();
return $this;
}
public function bind($stmt, $champs) {
if (!is_array($champs)) {
$champs = [$champs];
}
foreach ($champs as $champ) {
$stmt->bindParam(":$champ", $this->$champ);
}
return $this;
}
}