| <?php |
| |
| include_once "User.php"; |
| include_once "config.php"; |
| |
| use \User as User; |
| |
| class DB |
| { |
| |
| public $pdo; |
| public $log; |
| |
| function __construct($log) |
| { |
| global $DB, $DB_USER, $DB_PASS; |
| $this->log = $log; |
| try { |
| $this->pdo = new PDO($DB, $DB_USER, $DB_PASS); |
| if($log) |
| $log->info("Connected to database $DB"); |
| } catch (PDOException $e) { |
| echo $e->getMessage(); |
| if($log) |
| $log->error($e->getMessage()); |
| } |
| } |
| |
| function add_user(User $user) |
| { |
| $columns = $this->getColumnNames("person"); |
| foreach ((array) $user as $key => $value) { |
| if (array_key_exists($key, (array) $columns)) { |
| $a[$key] = $value; |
| } |
| } |
| $keys = array_keys($a); |
| $sql = "INSERT INTO person (" . implode(", ", $keys) . ") \n"; |
| $sql .= "VALUES ( :" . implode(", :", $keys) . ")"; |
| $q = $this->pdo->prepare($sql); |
| $i = 1; |
| foreach ($a as $value) |
| $q->bindParam($i++, $value); |
| $this->log->debug($sql); |
| return $q->execute($a); |
| } |
| |
| function getColumnNames($table) |
| { |
| $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; |
| try { |
| $stmt = $this->pdo->prepare($sql); |
| $stmt->bindValue(':table', $table, PDO::PARAM_STR); |
| $stmt->execute(); |
| $output = array(); |
| while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { |
| $output[$row['COLUMN_NAME']] = $row['COLUMN_NAME']; |
| } |
| return $output; |
| } catch (PDOException $pe) { |
| trigger_error('Could not connect to MySQL database. ' . $pe->getMessage(), E_USER_ERROR); |
| } |
| } |
| |
| function mail_count($email) |
| { |
| $sql = "SELECT COUNT(*) FROM person WHERE email = :email"; |
| try { |
| $stmt = $this->pdo->prepare($sql); |
| $stmt->bindValue(':email', $email, PDO::PARAM_STR); |
| $stmt->execute(); |
| $row = $stmt->fetch(PDO::FETCH_ASSOC); |
| return $row['COUNT(*)']; |
| } catch (PDOException $pe) { |
| trigger_error('Could not connect to MySQL database. ' . $pe->getMessage(), E_USER_ERROR); |
| } |
| } |
| } |