blob: e1be86e6da03c5f51588fe11714adf20d0600ec3 [file] [log] [blame]
Marc Kupietzb5ad9352023-03-09 08:15:35 +01001<?php
2
3include_once "User.php";
4include_once "config.php";
5
6use \User as User;
7
Marc Kupietz145f5b92023-03-09 20:39:31 +01008class DB
Marc Kupietzb5ad9352023-03-09 08:15:35 +01009{
Marc Kupietz145f5b92023-03-09 20:39:31 +010010
11 public $pdo;
12 public $log;
13
14 function __construct($log)
15 {
16 global $DB, $DB_USER, $DB_PASS;
17 $this->log = $log;
18 try {
19 $this->pdo = new PDO($DB, $DB_USER, $DB_PASS);
20 if($log)
21 $log->info("Connected to database $DB");
22 } catch (PDOException $e) {
23 echo $e->getMessage();
24 if($log)
25 $log->error($e->getMessage());
Marc Kupietzb5ad9352023-03-09 08:15:35 +010026 }
27 }
Marc Kupietzb5ad9352023-03-09 08:15:35 +010028
Marc Kupietz145f5b92023-03-09 20:39:31 +010029 function add_user(User $user)
30 {
31 $columns = $this->getColumnNames("person");
32 foreach ((array) $user as $key => $value) {
33 if (array_key_exists($key, (array) $columns)) {
34 $a[$key] = $value;
35 }
Marc Kupietzb5ad9352023-03-09 08:15:35 +010036 }
Marc Kupietz145f5b92023-03-09 20:39:31 +010037 $keys = array_keys($a);
38 $sql = "INSERT INTO person (" . implode(", ", $keys) . ") \n";
39 $sql .= "VALUES ( :" . implode(", :", $keys) . ")";
40 $q = $this->pdo->prepare($sql);
41 $i = 1;
42 foreach ($a as $value)
43 $q->bindParam($i++, $value);
44 $this->log->debug($sql);
45 return $q->execute($a);
46 }
47
48 function getColumnNames($table)
49 {
50 $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
51 try {
52 $stmt = $this->pdo->prepare($sql);
53 $stmt->bindValue(':table', $table, PDO::PARAM_STR);
54 $stmt->execute();
55 $output = array();
56 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
57 $output[$row['COLUMN_NAME']] = $row['COLUMN_NAME'];
58 }
59 return $output;
60 } catch (PDOException $pe) {
61 trigger_error('Could not connect to MySQL database. ' . $pe->getMessage(), E_USER_ERROR);
62 }
63 }
64
65 function mail_count($email)
66 {
67 $sql = "SELECT COUNT(*) FROM person WHERE email = :email";
68 try {
69 $stmt = $this->pdo->prepare($sql);
70 $stmt->bindValue(':email', $email, PDO::PARAM_STR);
71 $stmt->execute();
72 $row = $stmt->fetch(PDO::FETCH_ASSOC);
73 return $row['COUNT(*)'];
74 } catch (PDOException $pe) {
75 trigger_error('Could not connect to MySQL database. ' . $pe->getMessage(), E_USER_ERROR);
76 }
Marc Kupietzb5ad9352023-03-09 08:15:35 +010077 }
78}