├── EasySQL.php ├── LICENSE ├── README.md └── examples ├── avg.php ├── count.php ├── delete.php ├── get.php ├── insert.php ├── limit-pages.php ├── limit.php ├── min-max.php ├── query.php ├── search.php ├── selectAll.php └── update.php /EasySQL.php: -------------------------------------------------------------------------------- 1 | host = $host; 40 | $this->username = $username; 41 | $this->password = $password; 42 | $this->database = $database; 43 | $this->charset = $charset; 44 | 45 | // Set up the PDO object with the given parameters 46 | $dsn = "mysql:host=$this->host;dbname=$this->database;charset=$this->charset"; 47 | $options = array( 48 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 49 | PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 50 | PDO::ATTR_EMULATE_PREPARES => false, 51 | ); 52 | try { 53 | $this->pdo = new PDO($dsn, $this->username, $this->password, $options); 54 | } catch (\PDOException $e) { 55 | throw new \PDOException($e->getMessage(), (int) $e->getCode()); 56 | } 57 | } 58 | 59 | /** 60 | * Inserts a new row into the specified table with the given data. 61 | * 62 | * @param string $table the name of the table 63 | * @param array $data an associative array of column names and values 64 | * 65 | * @return bool true if the insert was successful, false otherwise 66 | */ 67 | public function insert($table, $data) 68 | { 69 | $columns = implode(', ', array_keys($data)); 70 | $placeholders = implode(', ', array_fill(0, count($data), '?')); 71 | $values = array_values($data); 72 | $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)"; 73 | $stmt = $this->pdo->prepare($sql); 74 | return $stmt->execute($values); 75 | } 76 | 77 | /** 78 | * Retrieves rows from the specified table that match the specified criteria. 79 | * 80 | * @param string $table the name of the table 81 | * @param string|array $columns the names of the columns to retrieve (default: *) 82 | * @param array $conditions an associative array of conditions for the query (default: array()) 83 | * @param array $options an associative array of options for the query (default: array()) 84 | * 85 | * @return array an array of rows that match the query criteria 86 | */ 87 | public function select($table, $columns = '*', $conditions = array(), $options = array()) 88 | { 89 | $sql = "SELECT $columns FROM $table"; 90 | $where = ''; 91 | $bindings = array(); 92 | if (!empty($conditions)) { 93 | $whereArray = array(); 94 | foreach ($conditions as $column => $value) { 95 | if (is_array($value)) { 96 | $operator = key($value); 97 | if ($operator === 'LIKE') { 98 | $value = "%{$value[$operator]}%"; 99 | } 100 | $whereArray[] = "$column $operator ?"; 101 | $bindings[] = $value; 102 | } else { 103 | $whereArray[] = "$column = ?"; 104 | $bindings[] = $value; 105 | } 106 | } 107 | $where = 'WHERE ' . implode(' AND ', $whereArray); 108 | } 109 | $sql .= " $where"; 110 | if (!empty($options)) { 111 | foreach ($options as $option => $value) { 112 | $sql .= " $option $value"; 113 | } 114 | } 115 | $stmt = $this->pdo->prepare($sql); 116 | $stmt->execute($bindings); 117 | return $stmt->fetchAll(); 118 | } 119 | 120 | /** 121 | * Updates rows in the specified table that match the specified criteria with the given data. 122 | * 123 | * @param string $table the name of the table 124 | * @param array $data an associative array of column names and new values 125 | * @param string $where the WHERE clause for the query (default: '') 126 | * @param array $bindings an array of values to bind to the placeholders in the WHERE clause (default: array()) 127 | * 128 | * @return bool true if the update was successful, false otherwise 129 | */ 130 | public function update($table, $data, $where = '', $bindings = array()) 131 | { 132 | $set = array(); 133 | foreach ($data as $column => $value) { 134 | $set[] = "$column = ?"; 135 | } 136 | $set = implode(', ', $set); 137 | $sql = "UPDATE $table SET $set"; 138 | if (!empty($where)) { 139 | $sql .= " WHERE $where"; 140 | } 141 | $values = array_values($data); 142 | $stmt = $this->pdo->prepare($sql); 143 | $values = array_merge($values, $bindings); 144 | return $stmt->execute($values); 145 | } 146 | 147 | /** 148 | * Delete rows from a table. 149 | * 150 | * @param string $table The name of the table to delete rows from. 151 | * @param string $where The WHERE clause for the delete statement. 152 | * @param array $bindings An array of parameter values to bind to the SQL statement. 153 | * 154 | * @return bool Whether the delete statement was successful. 155 | */ 156 | public function delete($table, $where = '', $bindings = array()) 157 | { 158 | $sql = "DELETE FROM $table"; 159 | if (!empty($where)) { 160 | $sql .= " WHERE $where"; 161 | } 162 | $stmt = $this->pdo->prepare($sql); 163 | return $stmt->execute($bindings); 164 | } 165 | 166 | /** 167 | * Get the number of rows in a table. 168 | * 169 | * @param string $table The name of the table to count rows in. 170 | * @param string $where The WHERE clause for the count statement. 171 | * @param array $bindings An array of parameter values to bind to the SQL statement. 172 | * 173 | * @return int The number of rows in the table. 174 | */ 175 | public function count($table, $where = '', $bindings = array()) 176 | { 177 | $sql = "SELECT COUNT(*) FROM $table"; 178 | if (!empty($where)) { 179 | $sql .= " WHERE $where"; 180 | } 181 | $stmt = $this->pdo->prepare($sql); 182 | $stmt->execute($bindings); 183 | return $stmt->fetchColumn(); 184 | } 185 | 186 | /** 187 | * Get the sum of a column in a table. 188 | * 189 | * @param string $table The name of the table to sum the column in. 190 | * @param string $column The name of the column to sum. 191 | * @param string $where The WHERE clause for the sum statement. 192 | * @param array $bindings An array of parameter values to bind to the SQL statement. 193 | * 194 | * @return int The sum of the column in the table. 195 | */ 196 | public function sum($table, $column, $where = '', $bindings = array()) 197 | { 198 | $sql = "SELECT SUM($column) FROM $table"; 199 | if (!empty($where)) { 200 | $sql .= " WHERE $where"; 201 | } 202 | $stmt = $this->pdo->prepare($sql); 203 | $stmt->execute($bindings); 204 | return $stmt->fetchColumn(); 205 | } 206 | 207 | /** 208 | * Calculates the average of a column in a table. 209 | * 210 | * @param string $table The name of the table to select from. 211 | * @param string $column The name of the column to calculate the average of. 212 | * @param string $where Optional WHERE clause to filter results. 213 | * @param array $bindings Optional parameter bindings for the WHERE clause. 214 | * 215 | * @return mixed The average of the column as a float, or FALSE on failure. 216 | */ 217 | public function avg($table, $column, $where = '', $bindings = array()) 218 | { 219 | $sql = "SELECT AVG($column) FROM $table"; 220 | if (!empty($where)) { 221 | $sql .= " WHERE $where"; 222 | } 223 | $stmt = $this->pdo->prepare($sql); 224 | $stmt->execute($bindings); 225 | return $stmt->fetchColumn(); 226 | } 227 | 228 | /** 229 | * Finds the minimum value of a column in a table. 230 | * 231 | * @param string $table The name of the table to select from. 232 | * @param string $column The name of the column to find the minimum of. 233 | * @param string $where Optional WHERE clause to filter results. 234 | * @param array $bindings Optional parameter bindings for the WHERE clause. 235 | * 236 | * @return mixed The minimum value of the column, or FALSE on failure. 237 | */ 238 | public function min($table, $column, $where = '', $bindings = array()) 239 | { 240 | $sql = "SELECT MIN($column) FROM $table"; 241 | if (!empty($where)) { 242 | $sql .= " WHERE $where"; 243 | } 244 | $stmt = $this->pdo->prepare($sql); 245 | $stmt->execute($bindings); 246 | return $stmt->fetchColumn(); 247 | } 248 | 249 | /** 250 | * Finds the maximum value of a column in a table. 251 | * 252 | * @param string $table The name of the table to select from. 253 | * @param string $column The name of the column to find the maximum of. 254 | * @param string $where Optional WHERE clause to filter results. 255 | * @param array $bindings Optional parameter bindings for the WHERE clause. 256 | * 257 | * @return mixed The maximum value of the column, or FALSE on failure. 258 | */ 259 | public function max($table, $column, $where = '', $bindings = array()) 260 | { 261 | $sql = "SELECT MAX($column) FROM $table"; 262 | if (!empty($where)) { 263 | $sql .= " WHERE $where"; 264 | } 265 | $stmt = $this->pdo->prepare($sql); 266 | $stmt->execute($bindings); 267 | return $stmt->fetchColumn(); 268 | } 269 | 270 | /** 271 | * Runs a SQL query and returns the results. 272 | * 273 | * @param string $sql The SQL query to run. 274 | * @param array $bindings Optional parameter bindings for the SQL query. 275 | * 276 | * @return array An array of results from the SQL query. 277 | */ 278 | public function query($sql, $bindings = array()) 279 | { 280 | $stmt = $this->pdo->prepare($sql); 281 | $stmt->execute($bindings); 282 | return $stmt->fetchAll(); 283 | } 284 | 285 | /** 286 | * Retrieves a row from a table by ID. 287 | * 288 | * @param string $table The name of the table to select from. 289 | * @param int $id The ID of the row to select. 290 | * 291 | * @return array The row from the table with the specified ID. 292 | */ 293 | public function get($table, $id) 294 | { 295 | $sql = "SELECT * FROM $table WHERE id = ?"; 296 | $stmt = $this->pdo->prepare($sql); 297 | $stmt->execute(array($id)); 298 | return $stmt->fetch(); 299 | } 300 | 301 | /** 302 | * Retrieves a row from a table by ID using a custom SQL query. 303 | * 304 | * @param string $table The name of the table to select from. 305 | * @param int $id The ID of the row to select. 306 | * @param string $columns The columns to select from the table. 307 | * 308 | * @return array The row from the table with the specified ID. 309 | * 310 | * @throws \Exception If the query file cannot be found. 311 | */ 312 | public function find($table, $id, $columns = '*') 313 | { 314 | $sql_file = "SELECT_BY_ID_$table.sql"; 315 | if (file_exists($sql_file)) { 316 | $sql = file_get_contents($sql_file); 317 | $stmt = $this->pdo->prepare($sql); 318 | $stmt->execute(array($id)); 319 | return $stmt->fetch(); 320 | } else { 321 | throw new \Exception("Cannot find query file: $sql_file"); 322 | } 323 | } 324 | 325 | /** 326 | * Retrieves multiple rows from a table. 327 | * 328 | * @param string $table The name of the table to select from. 329 | * @param string $columns The columns to select from the table. 330 | * @param string $where The WHERE clause of the SQL query. 331 | * @param array $bindings Optional parameter bindings for the SQL query. 332 | * 333 | * @return array An array of rows from the table that match the WHERE clause. 334 | */ 335 | public function findAll($table, $columns = '*', $where = '', $bindings = array()) 336 | { 337 | $sql = "SELECT $columns FROM $table"; 338 | if (!empty($where)) { 339 | $sql .= " WHERE $where"; 340 | } 341 | $stmt = $this->pdo->prepare($sql); 342 | $stmt->execute($bindings); 343 | return $stmt->fetchAll(); 344 | } 345 | 346 | /** 347 | * Saves data to a table, either by updating an existing row or creating a new one. 348 | * 349 | * @param string $table The name of the table to save to. 350 | * @param array $data An associative array of column names and values to save. 351 | * 352 | * @return bool True if the save was successful, false otherwise. 353 | */ 354 | public function save($table, $data) 355 | { 356 | if (isset($data['id'])) { 357 | $set = array(); 358 | foreach ($data as $column => $value) { 359 | if ($column !== 'id') { 360 | $set[] = "$column = ?"; 361 | } 362 | } 363 | $set = implode(', ', $set); 364 | $sql = "UPDATE $table SET $set WHERE id = ?"; 365 | $values = array_values($data); 366 | $stmt = $this->pdo->prepare($sql); 367 | return $stmt->execute(array_merge($values, array($data['id']))); 368 | } else { 369 | $columns = implode(', ', array_keys($data)); 370 | $placeholders = implode(', ', array_fill(0, count($data), '?')); 371 | $values = array_values($data); 372 | $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)"; 373 | $stmt = $this->pdo->prepare($sql); 374 | return $stmt->execute($values); 375 | } 376 | } 377 | } 378 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 ReactMVC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasySQL 2 | Class EasySQL provides an easy-to-use interface for basic MySQL database operations. 3 | -------------------------------------------------------------------------------- /examples/avg.php: -------------------------------------------------------------------------------- 1 | avg('customers', 'age', $where, $bindings); 12 | echo "The average age of customers from the USA is $avg"; -------------------------------------------------------------------------------- /examples/count.php: -------------------------------------------------------------------------------- 1 | count('users', $where, $bindings); 12 | echo "There are $count active users"; -------------------------------------------------------------------------------- /examples/delete.php: -------------------------------------------------------------------------------- 1 | delete('users', $where, $bindings); 12 | if ($result) { 13 | echo 'Delete successful'; 14 | } else { 15 | echo 'Delete failed'; 16 | } -------------------------------------------------------------------------------- /examples/get.php: -------------------------------------------------------------------------------- 1 | get('users', 4); 8 | 9 | // Output the values of the row 10 | echo "Name: {$row['name']}, Email: {$row['email']}"; -------------------------------------------------------------------------------- /examples/insert.php: -------------------------------------------------------------------------------- 1 | 'John Doe', 7 | 'email' => 'johndoe@example.com', 8 | 'password' => 'mypass' 9 | ); 10 | $result = $db->insert('users', $data); 11 | if ($result) { 12 | echo 'New user added successfully.'; 13 | } else { 14 | echo 'Error adding new user.'; 15 | } -------------------------------------------------------------------------------- /examples/limit-pages.php: -------------------------------------------------------------------------------- 1 | "$offset, $perPage" 15 | ); 16 | 17 | // Perform the query and retrieve the results 18 | $results = $db->select('users', '*', $conditions, $options); 19 | 20 | // Count the total number of results 21 | $totalResults = count($db->select('users')); 22 | 23 | // Calculate the total number of pages 24 | $totalPages = ceil($totalResults / $perPage); 25 | 26 | // Output the results and pagination links 27 | foreach ($results as $result) { 28 | echo $result['id'] . ': ' . $result['name'] . '
'; 29 | } 30 | 31 | echo '
'; 32 | 33 | if ($totalPages > 1) { 34 | echo 'Pages: '; 35 | for ($i = 1; $i <= $totalPages; $i++) { 36 | if ($i == $page) { 37 | echo "$i "; 38 | } else { 39 | echo "$i "; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /examples/limit.php: -------------------------------------------------------------------------------- 1 | '2' 8 | ); 9 | 10 | $results = $db->select('users', '*', array(), $options); 11 | 12 | print_r($results); -------------------------------------------------------------------------------- /examples/min-max.php: -------------------------------------------------------------------------------- 1 | min('users', 'id', $where, $bindings); 12 | echo "The minimum id of John Doe name is $minID
"; 13 | 14 | // Find the maximum id and output it 15 | $maxID = $db->max('users', 'id', $where, $bindings); 16 | echo "The maximum id of John Doe name is $maxID"; -------------------------------------------------------------------------------- /examples/query.php: -------------------------------------------------------------------------------- 1 | query($sql, $bindings); 12 | foreach ($results as $row) { 13 | echo "Name: {$row['name']}, Age: {$row['age']}, Email: {$row['email']}
"; 14 | } -------------------------------------------------------------------------------- /examples/search.php: -------------------------------------------------------------------------------- 1 | select('users', '*', ['name' => ['LIKE' => 'H']]); 7 | foreach ($users as $user) { 8 | echo $user['id'] . ': ' . $user['name'] . ' - ' . $user['email'] . '
'; 9 | } -------------------------------------------------------------------------------- /examples/selectAll.php: -------------------------------------------------------------------------------- 1 | select('users'); 7 | foreach ($users as $user) { 8 | echo $user['id'] . ': ' . $user['name'] . ' - ' . $user['email'] . '
'; 9 | } -------------------------------------------------------------------------------- /examples/update.php: -------------------------------------------------------------------------------- 1 | 'John Doe', 9 | 'email' => 'johndoe@example.com' 10 | ); 11 | $where = 'id = ?'; 12 | $bindings = array(1); 13 | 14 | // Perform the update and check if it was successful 15 | $result = $db->update('users', $data, $where, $bindings); 16 | if ($result) { 17 | echo 'Update successful'; 18 | } else { 19 | echo 'Update failed'; 20 | } --------------------------------------------------------------------------------