diff --git a/README.md b/README.md index 7dddbb1..3d1f1a0 100644 --- a/README.md +++ b/README.md @@ -15,65 +15,76 @@ ## Example usage ```php -$host = 'localhost'; -$port = 3306; -$dbName = 'my_database'; -$username = 'username'; -$password = 'password'; -$options = [ - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, -]; - -$db = new SimpleDB($host, $port, $dbName, $username, $password); -``` - -## Example Insert - -```php -$db->insert('users', ['name' => 'Alice', 'status' => 'active']); -echo 'Last Insert ID: ' . $db->getLastInsertId(); - -``` +update('users', ['status' => 'inactive'], 'name = ?', ['Alice']); - -``` - -## Example Delete - -```php -$db->delete('users', 'name = ?', ['Alice']); +use SimpleDB\SimpleDB; -``` - -## Example Transaction - -```php -$db->beginTransaction(); try { - $db->insert('users', ['name' => 'Bob', 'status' => 'active']); - $db->update('users', ['status' => 'inactive'], 'name = ?', ['Bob']); - $db->commit(); + // Create a new instance of the SimpleDB class + $db = new SimpleDB(dbName: 'my_database', username: 'username', password: 'password'); + + // Check if the connection is successful + if ($db->isConnected()) { + echo "Connected to the database successfully.\n"; + } else { + echo "Failed to connect to the database.\n"; + } + + // Example: Executing a query to fetch all rows from a table + $sql = 'SELECT * FROM `users`'; + $result = $db->fetchAll($sql); + + echo "Data from users table:\n"; + foreach ($result as $row) { + print_r($row); + } + + // Example: Inserting a new record into the table + $insertData = [ + 'username' => 'john_doe', + 'email' => 'john.doe@example.com', + ]; + + if ($db->insert('users', $insertData)) { + echo "Record inserted successfully.\n"; + } else { + echo "Failed to insert record.\n"; + } + + // Example: Updating a record in the table + $updateData = [ + 'email' => 'john.new@example.com', + ]; + $where = "username = 'john_doe'"; + + if ($db->update('users', $updateData, $where)) { + echo "Record updated successfully.\n"; + } else { + echo "Failed to update record.\n"; + } + + // Example: Deleting a record from the table + $where = "username = 'john_doe'"; + + if ($db->delete('users', $where)) { + echo "Record deleted successfully.\n"; + } else { + echo "Failed to delete record.\n"; + } + + // Example: Truncating the users table + if ($db->truncate('users')) { + echo "Table truncated successfully.\n"; + } else { + echo "Failed to truncate table.\n"; + } + } catch (Exception $e) { - $db->rollBack(); - echo 'Transaction failed: ' . $e->getMessage(); + echo 'Error: ' . $e->getMessage() . "\n"; } -``` - -## Example Connection Test - -```php - -if ($db->isConnected()) { - echo 'Connected to the database'; -} else { - echo 'Not connected to the database'; -} ``` diff --git a/src/SimpleDB.php b/src/SimpleDB.php index 3915f56..8a9346c 100644 --- a/src/SimpleDB.php +++ b/src/SimpleDB.php @@ -5,14 +5,21 @@ use PDO; use PDOException; use Exception; -use PDOStatement; // Import PDOStatement class +use PDOStatement; class SimpleDB { private $pdo; private $queryCount = 0; private $queries = []; - public function __construct(string $host, string $port, string $dbName, string $username, string $password, array $options = []) { + public function __construct( + string $host = 'localhost', + string $port = '3306', + string $dbName, + string $username, + string $password, + array $options = [] + ) { $dsn = "mysql:host=$host;port=$port;dbname=$dbName"; try { $defaultOptions = [ @@ -58,15 +65,16 @@ public function fetchAll(string $sql, array $params = []): array { } private function getTableColumns(string $table): array { - $stmt = $this->query("DESCRIBE $table"); + $stmt = $this->query("DESCRIBE `$table`"); $columns = $stmt->fetchAll(PDO::FETCH_COLUMN); return $columns; } - public function execute(string $sql): PDOStatement { // Return SimpleDB\PDOStatement + public function execute(string $sql): PDOStatement { try { $startTime = microtime(true); - $stmt = $this->pdo->query($sql); + $stmt = $this->pdo->prepare($sql); + $stmt->execute(); $endTime = microtime(true); $executionTime = $endTime - $startTime; @@ -76,15 +84,7 @@ public function execute(string $sql): PDOStatement { // Return SimpleDB\PDOState 'execution_time' => $executionTime ]; - return new class($stmt) extends PDOStatement { // Return SimpleDB\PDOStatement - private $stmt; - - public function __construct(PDOStatement $stmt) { // Accept PDOStatement as argument - $this->stmt = $stmt; - } - - // Implement the necessary methods from PDOStatement - }; + return $stmt; } catch (PDOException $e) { throw new Exception('Query execution failed: ' . $e->getMessage(), 0, $e); } @@ -105,11 +105,11 @@ public function insert(string $table, array $data): bool { if (empty($data)) { throw new Exception('Insert data cannot be empty.'); } - - $columns = implode(", ", array_keys($data)); - $placeholders = implode(", ", array_fill(0, count($data), '?')); - $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)"; - + + $columns = implode(', ', array_map(fn($col) => "`$col`", array_keys($data))); + $placeholders = implode(', ', array_fill(0, count($data), '?')); + $sql = "INSERT INTO `$table` ($columns) VALUES ($placeholders)"; + try { return $this->query($sql, array_values($data))->rowCount() > 0; } catch (PDOException $e) { @@ -118,13 +118,13 @@ public function insert(string $table, array $data): bool { } public function update(string $table, array $data, string $where, array $params = []): bool { - $setClause = implode(", ", array_map(fn($key) => "$key = ?", array_keys($data))); - $sql = "UPDATE $table SET $setClause WHERE $where"; + $setClause = implode(', ', array_map(fn($key) => "`$key` = ?", array_keys($data))); + $sql = "UPDATE `$table` SET $setClause WHERE $where"; return $this->query($sql, array_merge(array_values($data), $params))->rowCount() > 0; } public function delete(string $table, string $where, array $params = []): bool { - $sql = "DELETE FROM $table WHERE $where"; + $sql = "DELETE FROM `$table` WHERE $where"; return $this->query($sql, $params)->rowCount() > 0; } @@ -152,4 +152,15 @@ public function isConnected(): bool { return false; } } + + public function truncate(string $table): bool { + $sql = "TRUNCATE TABLE `$table`"; + try { + $this->execute($sql); + return true; + } catch (PDOException $e) { + throw new Exception('Truncate query execution failed: ' . $e->getMessage(), 0, $e); + } + } } +