Skip to content

Commit

Permalink
2.4.33
Browse files Browse the repository at this point in the history
- added truncate method
- added default values for connection arguments
- updated README
  • Loading branch information
PJanisio authored Jun 7, 2024
1 parent 9c5d7de commit 3ac2b4a
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 74 deletions.
115 changes: 63 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();

```
<?php

## Example Update
require 'path/to/SimpleDB.php'; // Adjust the path to where your SimpleDB.php is located

```php
$db->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' => '[email protected]',
];

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' => '[email protected]',
];
$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';
}

```

Expand Down
55 changes: 33 additions & 22 deletions src/SimpleDB.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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;

Expand All @@ -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);
}
Expand All @@ -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) {
Expand All @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
}

0 comments on commit 3ac2b4a

Please sign in to comment.