· 4 years ago · Jul 01, 2021, 08:38 PM
1<?php
2
3class ConnectToDatabase
4{
5 protected static $connection;
6
7 public function getConnection()
8 {
9 if (!isset(self::$connection)) {
10 $config = parse_ini_file('config.ini');
11
12 self::$connection = new mysqli('localhost', $config['username'], $config['password']);
13 }
14
15 if (self::$connection === false) {
16 return false;
17 }
18
19 return self::$connection;
20 }
21
22 public function initializeDatabase($selectedDatabase)
23 {
24 $connection = $this->getConnection();
25 if ($connection->connect_error) {
26 die("Error connecting to the database");
27 }
28 $db_selected = $connection->select_db($selectedDatabase);
29
30 if (!$db_selected) {
31 $sql = "CREATE DATABASE $selectedDatabase";
32 if ($connection->query($sql) === TRUE) {
33 echo "Database created successfuly!";
34 }
35 }
36 }
37
38 public function validateEmail($email): bool
39 {
40 if (!isset($email)) {
41 return false;
42 }
43 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
44 return false;
45 }
46 return true;
47 }
48
49 public function createTable($tableName)
50 {
51 $sql = "CREATE TABLE IF NOT EXISTS $tableName (
52 ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
53 Email VARCHAR(30) NOT NULL)";
54
55 $connection = $this->getConnection();
56
57 if ($connection->connect_error) {
58 die("Error connecting to the database");
59 }
60
61 if ($connection->query($sql) === TRUE) {
62 echo "Database created successfuly";
63 }
64 }
65}
66