SQLDatabase.php (3077B)
1 <?php 2 3 namespace Lollipop { 4 use mysqli; 5 6 class SQLDatabase 7 { 8 public mysqli $conn; 9 10 function __construct(string $host, string $username, string $password, string $database = null, int $port = null) 11 { 12 $this->conn = new mysqli($host, $username, $password, $database, $port); 13 } 14 15 function get(string $table_class) 16 { 17 /* this function accepts a $table_name creates a Database object with the class $table_name 18 * retuns a Database object 19 */ 20 $cls = new $table_class($this); 21 return $cls; 22 } 23 24 function all_where(string $table_name, array $vars) 25 { 26 /* this function accepts a table name and an array[$column_name => $value] 27 * statement is select * from $table_name where $column_name = $value AND etc... 28 * returns an array of classes 29 */ 30 if (!sizeof($vars)) { 31 return []; 32 } 33 $cls = new $table_name($this); 34 35 $sql = "SELECT * FROM {$cls->get_table()} WHERE "; 36 $params = []; 37 38 $i = 0; 39 foreach ($vars as $key => $value) { 40 if ($i > 0) { 41 $sql .= ' AND '; 42 } 43 $sql .= " $key LIKE ?"; 44 $params[] = $value; 45 $i++; 46 } 47 48 $stmt = $this->conn->prepare($sql); 49 $stmt->execute($params); 50 $result = $stmt->get_result(); 51 52 if (!$result || $result->num_rows == 0) { 53 return []; 54 } 55 56 $objects = []; 57 while ($row = $result->fetch_assoc()) { 58 $o = new $table_name($this); 59 $o->setData($row); 60 $objects[] = $o; 61 } 62 return $objects; 63 } 64 65 function all(string $table_name) 66 { 67 /* loads whole table $table_name 68 * returns array of objects 69 */ 70 $cls = new $table_name($this); 71 72 $sql = "SELECT * FROM {$cls->get_table()}"; 73 74 $result = $this->conn->query($sql); 75 76 if (!$result || $result->num_rows == 0) { 77 return []; 78 } 79 80 $objects = []; 81 while ($row = $result->fetch_assoc()) { 82 $o = new $table_name($this); 83 $o->setData($row); 84 $objects[] = $o; 85 } 86 return $objects; 87 } 88 public function getDateRange(string $table_name, array $query, $order) 89 { 90 if($query == null) 91 return []; 92 93 $cls = new $table_name($this); 94 95 $sql = "SELECT * FROM {$cls->get_table()} WHERE "; 96 $index = 0; 97 $values = []; 98 foreach($query as $key => $q) { 99 foreach ($q as $k => $value) { 100 if ($index > 0) { 101 $sql .= " AND "; 102 } 103 $sql .= "{$key} {$k} ?"; 104 $values[] = $value; 105 $index++; 106 } 107 } 108 109 $sql .= " ORDER BY date_time " . $order; 110 $sql .= " LIMIT 1000"; 111 $stmt = $this->conn->prepare($sql); 112 $stmt->execute($values); 113 $result = $stmt->get_result(); 114 115 if ($result->num_rows == 0) { 116 return []; 117 } 118 119 $objects = []; 120 while ($row = $result->fetch_assoc()) { 121 $o = new $table_name($this); 122 $o->setData($row); 123 $objects[] = $o; 124 } 125 return $objects; 126 } 127 } 128 } 129 ?>