From 433bc982d18b0736a4c7f084da670e0909276726 Mon Sep 17 00:00:00 2001 From: aryan083 Date: Sat, 6 Jul 2024 14:24:08 +0530 Subject: [PATCH] changed a lot of things change the DbConnection to PDO object from mysqli. Changed almost all the methods to have a where clause to help with finding things in database added two new function selectByConditions and InsertandReturnLastInsertId optimised index update readme to have your github --- README.md | 127 ++++++++++++++++++++++++++++++------- config.php | 2 + database/db_connection.php | 21 +++--- database/delete.php | 41 ++++++++++-- database/index.php | 124 +++++++++++++++++++++++++++--------- database/insert.php | 61 ++++++++++++++---- database/select.php | 61 +++++++++++++++--- database/update.php | 49 +++++++++++--- 8 files changed, 390 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index 068ea63..16b5687 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,144 @@ # php-crud this is a helper for php crud operation. -
+ # How to Use -folder sceenshot +folder screenshot + +Create a new file `index.php` + +Then, open `index.php` & `config.php` in your text editor. -create a new file `index.php` +In `config.php`, you need to set up the database connection first: -then , open `index.php` & `config.php` in your text editor . +```php +define("DB_HOST", "localhost"); // your host name +define("DB_USER", "your_username"); // your database username +define("DB_PASS", "your_password"); // your database password +define("DB_NAME", "your_database_name"); // your database name -In `config.php` , You need to setup Database connection as first. +// Message Settings +define('insertSuccess', 'Insert Successfully'); +define('updateSuccess', 'Update Successfully'); +define('deleteSuccess', 'Deleted Successfully'); -then `index.php`, -put these at the top , +In index.php, include the necessary files at the top: ``` include 'database/index.php';``` +include 'db_connection.php'; +include 'config.php'; # For Insert : +```php +`DB::insert($table, $data); +```` +`$table` = its your table name, -`DB::insert($table, $data);` +`$data`: An associative array where the key will be the column name of your table. -`$table` = its your table name, +### Example : +````php +$table = 'users'; +$data = [ + 'name' => 'John Doe', + 'email' => 'john@example.com' +]; +DB::insert($table, $data); +```` + +# For selectAll : +````php +DB::select($table); +```` +`$table`: The name of your table. + +### Example : + +````php +$results = DB::selectAll($table); + +foreach ($results as $row) { + echo $row['name']; +} +```` -`$data` = A array ,where key will be the column of your table. +# For Select with Conditions : -# For select : +````php +$conditions = ['id' => 1, 'status' => 'active']; + +$results = DB::selectWithConditions($table, $conditions); + +foreach ($results as $row) { + echo $row['name']; +} +```` +`$table`: The name of your table. +`$conditions`: An associative array of column names and values for the WHERE clause. -`DB::select($table);` ### Example : -```bash -$results = DB::select($table); +````php -while ($rows = $results->fetch_assoc()) { +$table = 'users'; +$conditions = ['status' => 'active']; +$results = DB::selectWithConditions($table, $conditions); - echo $rows['name']; +foreach ($results as $row) { + echo $row['name']; } -``` +```` + # For Update : -`DB::update($table, $data, $id);` +````php +$data = ['name' => 'New Name']; +$conditions = ['id' => 1]; +DB::update($table, $data, $conditions); +```` -# For Delete : +`$table`: The name of your table. +`$data`: An associative array where the key will be the column name of your table. +`$conditions`: An associative array of column names and values for the WHERE clause -`DB::delete($table, $id);` +### Example: +````php +$table = 'users'; +$data = ['name' => 'Jane Doe']; +$conditions = ['id' => 1]; +DB::update($table, $data, $conditions); +```` ---- + +# For Delete : +````php +$conditions = ['id' => 1]; +DB::delete($table, $conditions); +```` +`$table`: The name of your table. +`$conditions`: An associative array of column names and values for the WHERE clause. + + +### Example +```php +$table = 'users'; +$conditions = ['id' => 1]; +DB::delete($table, $conditions); +``` ### For more Links -- [GitHub](https://github.com/IANirab/) +- [GitHub](https://github.com/Ok9xNirab/) - [Facebook](https://web.facebook.com/istiaq.nirab.1) **Enjoy!** + +### Few Notes after the update +all `$conditions` are supposed to be a key value pairs where keys are column names and values are values of those columns + diff --git a/config.php b/config.php index 8db2069..3bee33e 100644 --- a/config.php +++ b/config.php @@ -8,3 +8,5 @@ define('insertSuccess', 'Insert Successfully'); define('updateSuccess', 'Update Successfully'); define('deleteSuccess', 'Deleted Successfully'); + +//suggest defining the tables here also as constants to avoid typos \ No newline at end of file diff --git a/database/db_connection.php b/database/db_connection.php index f4d42cc..dbf4da1 100644 --- a/database/db_connection.php +++ b/database/db_connection.php @@ -12,6 +12,7 @@ class dbConnection private $user; private $pass; private $dbname; + private $conn; public function __construct($host, $user, $pass, $dbname) { @@ -19,16 +20,20 @@ public function __construct($host, $user, $pass, $dbname) $this->user = $user; $this->pass = $pass; $this->dbname = $dbname; + + + try { + $dsn = "mysql:host=$this->host;dbname=$this->dbname"; + $this->conn = new PDO($dsn, $this->user, $this->pass); + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + echo "Database Not Connected: " . $e->getMessage(); + } } - public function connection() + public function getConnection() { - // Create connection - $conn = new mysqli($this->host, $this->user, $this->pass, $this->dbname); - // Check connection - if ($conn->connect_error) { - echo "Database Not Connected !!"; - } - return $conn; + return $this->conn; } } +?> diff --git a/database/delete.php b/database/delete.php index dab8d20..6599ff9 100644 --- a/database/delete.php +++ b/database/delete.php @@ -4,18 +4,47 @@ class delete { private $conn; private $table; + + /** + * Constructor to initialize connection and table. + * + * @param PDO $conn The PDO connection object. + * @param string $table The name of the table. + */ public function __construct($conn, $table) { $this->conn = $conn; $this->table = $table; } - public function deleteData($id) + + /** + * Deletes records from the table based on the provided conditions. + * + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return string|null The success message or null if an error occurs. + */ + public function deleteData($conditions) { - $delete = "DELETE FROM " . $this->table . " WHERE id='$id'"; - $result = $this->conn->query($delete); - $this->conn->close(); - if ($result != null) { - return $dbname = deleteSuccess; + $whereClause = ""; + $params = []; + + foreach ($conditions as $column => $value) { + $whereClause .= "$column = :$column AND "; + $params[$column] = $value; + } + + // Remove the trailing ' AND ' + $whereClause = rtrim($whereClause, " AND "); + + $stmt = $this->conn->prepare("DELETE FROM $this->table WHERE $whereClause"); + + try { + $stmt->execute($params); + return deleteSuccess; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return null; } } } +?> diff --git a/database/index.php b/database/index.php index a0f5c09..9d0d312 100644 --- a/database/index.php +++ b/database/index.php @@ -1,54 +1,116 @@ connection(), $table); - $row = $select->selectData(); - return $row; + return $db->getConnection(); } - static function update($table, $data, $id = null) + /** + * Selects all records from a specified table. + * + * @param string $table The name of the table to select from. + * @return array An associative array of all records in the table or an empty array if an error occurs. + */ + static function selectAll($table) { - $host = DB_HOST; - $user = DB_USER; - $pass = DB_PASS; - $dbname = DB_NAME; - $db = new dbConnection($host, $user, $pass, $dbname); - $select = new update($db->connection(), $table); - $row = $select->updateData($data, $id); - return $row; + $conn = self::getDBConnection(); + $select = new select($conn, $table); + return $select->selectAllData(); + } + + /** + * Selects records from a table based on provided conditions. + * + * @param string $table The name of the table to select from. + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return array An associative array of selected records or an empty array if an error occurs. + */ + static function selectWithConditions($table, $conditions) + { + $conn = self::getDBConnection(); + $select = new select($conn, $table); + return $select->selectByConditions($conditions); + } + + /** + * Updates records in a table based on provided data and conditions. + * + * @param string $table The name of the table to update. + * @param array $data An associative array of column names and values to update. + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return string|null The success message or null if an error occurs. + */ + static function update($table, $data, $conditions) + { + $conn = self::getDBConnection(); + $update = new update($conn, $table); + return $update->updateData($data, $conditions); } + /** + * Inserts data into a table. + * + * @param string $table The name of the table to insert into. + * @param array $data An associative array of column names and values to insert. + * @return string|null The success message or null if an error occurs. + */ static function insert($table, $data) { - $host = DB_HOST; - $user = DB_USER; - $pass = DB_PASS; - $dbname = DB_NAME; - $db = new dbConnection($host, $user, $pass, $dbname); - $select = new insert($db->connection(), $table); - $row = $select->insertData($data); - return $row; + $conn = self::getDBConnection(); + $insert = new insert($conn, $table); + return $insert->insertData($data); } - static function delete($table, $id) + /** + * Inserts data into a table and returns the last inserted ID. + * + * @param string $table The name of the table to insert into. + * @param array $data An associative array of column names and values to insert. + * @return string|null The last inserted ID or null if an error occurs. + */ + static function insertAndRetrunID($table, $data) { - $host = DB_HOST; - $user = DB_USER; - $pass = DB_PASS; - $dbname = DB_NAME; - $db = new dbConnection($host, $user, $pass, $dbname); - $select = new delete($db->connection(), $table); - $row = $select->deleteData($id); - return $row; + $conn = self::getDBConnection(); + $insert = new insert($conn, $table); + return $insert->insertDataReturnId($data); + } + + /** + * Deletes records from a table based on provided conditions. + * + * @param string $table The name of the table to delete from. + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return string|null The success message or null if an error occurs. + */ + static function delete($table, $conditions) + { + $conn = self::getDBConnection(); + $delete = new delete($conn, $table); + return $delete->deleteData($conditions); } } +?> diff --git a/database/insert.php b/database/insert.php index 19ca209..2c63f17 100644 --- a/database/insert.php +++ b/database/insert.php @@ -2,28 +2,65 @@ class insert { + + private $conn; private $table; + + /** + * Constructor to initialize connection and table. + * + * @param PDO $conn The PDO connection object. + * @param string $table The name of the table. + */ public function __construct($conn, $table) { $this->conn = $conn; $this->table = $table; } + + /** + * Inserts data into the table. + * + * @param array $data An associative array of column names and values. + * @return string|null The success message or null if an error occurs. + */ public function insertData($data) { - $key = array_keys($data); - $value = array_values($data); - $allkey = $key[0]; - $allvalue = "'$value[0]'"; - for ($i = 1; $i < count($key); $i++) { - $allkey .= ',' . $key[$i]; - $allvalue .= ',' . "'$value[$i]'"; + $columns = implode(", ", array_keys($data)); + $placeholders = ":" . implode(", :", array_keys($data)); + $stmt = $this->conn->prepare("INSERT INTO $this->table ($columns) VALUES ($placeholders)"); + + try { + $stmt->execute($data); + return insertSuccess; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return null; } - $insert = "INSERT INTO " . $this->table . " ($allkey) values ($allvalue)"; - $result = $this->conn->query($insert); - $this->conn->close(); - if ($result != null) { - return $dbname = insertSuccess; + } + + + //Note from contributor: This function is only added cuase it is very useful in many projects + /** + * Inserts data into the table and returns the last inserted ID. + * + * @param array $data An associative array of column names and values. + * @return int|string|null The last inserted ID or null if an error occurs. + */ + public function insertDataReturnId($data) + { + $columns = implode(", ", array_keys($data)); + $placeholders = ":" . implode(", :", array_keys($data)); + $stmt = $this->conn->prepare("INSERT INTO $this->table ($columns) VALUES ($placeholders)"); + + try { + $stmt->execute($data); + return $this->conn->lastInsertId(); + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return null; } } } +?> diff --git a/database/select.php b/database/select.php index c63a5e6..3d24d21 100644 --- a/database/select.php +++ b/database/select.php @@ -4,21 +4,66 @@ class select { private $conn; private $table; - public function __construct($conn, $table) + /** + * Constructor to initialize connection and table. + * + * @param PDO $conn The PDO connection object. + * @param string $table The name of the table. + */ public function __construct($conn, $table) { $this->conn = $conn; $this->table = $table; } - public function selectData() + + /** + * Selects all data from the table. + * + * @return array An associative array of all records in the table or an empty array if an error occurs. + */ + public function selectAllData() { - $data = "SELECT * FROM " . $this->table; - $result = $this->conn->query($data); + $stmt = $this->conn->prepare("SELECT * FROM $this->table"); + + try { + $stmt->execute(); + $result = $stmt->fetchAll(PDO::FETCH_ASSOC); + return $result; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return []; + } + } + + /** + * Selects data from the table based on the provided conditions. + * + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return array An associative array of the selected records or an empty array if an error occurs. + */ + public function selectByConditions($conditions) + { + $whereClause = ""; + $params = []; + + foreach ($conditions as $column => $value) { + $whereClause .= "$column = :$column AND "; + $params[$column] = $value; + } + + // Remove the trailing ' AND ' or the last AND that was added by the loop + $whereClause = rtrim($whereClause, " AND "); + + $query = "SELECT * FROM $this->table WHERE $whereClause"; + $stmt = $this->conn->prepare($query); - if ($result->num_rows > 0) { + try { + $stmt->execute($params); + $result = $stmt->fetchAll(PDO::FETCH_ASSOC); return $result; - } else { - echo "0 results"; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return []; } - $this->conn->close(); } } +?> diff --git a/database/update.php b/database/update.php index f150ee0..5747a83 100644 --- a/database/update.php +++ b/database/update.php @@ -4,22 +4,53 @@ class update { private $conn; private $table; + + /** + * Constructor to initialize connection and table. + * + * @param PDO $conn The PDO connection object. + * @param string $table The name of the table. + */ public function __construct($conn, $table) { $this->conn = $conn; $this->table = $table; } - public function updateData($data, $id) + + /** + * Updates records in the table based on the provided conditions. + * + * @param array $data An associative array of column names and values to update. + * @param array $conditions An associative array of column names and values for the WHERE clause. + * @return string|null The success message or null if an error occurs. + */ + public function updateData($data, $conditions) { - $key = array_keys($data); - $value = array_values($data); - for ($i = 0; $i < count($key); $i++) { - $update = "UPDATE " . $this->table . " SET " . $key[$i] . "='$value[$i]' WHERE id = $id"; - $result = $this->conn->query($update); + $setString = ""; + $params = []; + + foreach ($data as $key => $value) { + $setString .= "$key = :$key, "; + $params[$key] = $value; } - $this->conn->close(); - if ($result != null) { - return $dbname = updateSuccess; + $setString = rtrim($setString, ", "); + + $whereClause = ""; + foreach ($conditions as $column => $value) { + $whereClause .= "$column = :$column AND "; + $params[$column] = $value; + } + $whereClause = rtrim($whereClause, " AND "); + + $stmt = $this->conn->prepare("UPDATE $this->table SET $setString WHERE $whereClause"); + + try { + $stmt->execute($params); + return updateSuccess; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage(); + return null; } } } +?>