Using Object-Oriented PHP with a database class is an excellent choice for modularity, reusability, and clean code. Below is a detailed explanation and a full implementation covering CRUD (Create, Read, Update, Delete) operations, along with WHERE, ORDER BY, and other conditions.
Step 1: Create a Database Class
Here’s a simple and reusable Database
class:
<?php
class Database {
private $conn;
public function __construct($host, $user, $pass, $dbname) {
$this->conn = new mysqli($host, $user, $pass, $dbname);
// Check for connection errors
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
// INSERT Method
public function insert($table, $data) {
$columns = implode(", ", array_keys($data));
$values = implode("', '", array_map([$this->conn, 'real_escape_string'], array_values($data)));
$sql = "INSERT INTO $table ($columns) VALUES ('$values')";
return $this->conn->query($sql);
}
// SELECT Method
public function select($table, $columns = "*", $conditions = "") {
$sql = "SELECT $columns FROM $table $conditions";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
return $result->fetch_all(MYSQLI_ASSOC);
}
return [];
}
// UPDATE Method
public function update($table, $data, $conditions) {
$set = [];
foreach ($data as $column => $value) {
$set[] = "$column = '" . $this->conn->real_escape_string($value) . "'";
}
$setQuery = implode(", ", $set);
$sql = "UPDATE $table SET $setQuery $conditions";
return $this->conn->query($sql);
}
// DELETE Method
public function delete($table, $conditions) {
$sql = "DELETE FROM $table $conditions";
return $this->conn->query($sql);
}
// Close the connection
public function close() {
$this->conn->close();
}
}
?>
Step 2: Use the Database Class
1. Inserting Data
$db = new Database("localhost", "username", "password", "database");
$data = [
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
];
if ($db->insert("users", $data)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . $db->conn->error;
}
2. Selecting Data with Conditions
// Fetch all records
$users = $db->select("users");
print_r($users);
// Fetch specific records with WHERE and ORDER BY
$conditions = "WHERE age > 20 ORDER BY name ASC";
$users = $db->select("users", "*", $conditions);
foreach ($users as $user) {
echo $user['name'] . " - " . $user['email'] . "<br>";
}
3. Updating Data
$data = [
'email' => 'newemail@example.com',
'age' => 35
];
$conditions = "WHERE name = 'John Doe'";
if ($db->update("users", $data, $conditions)) {
echo "Data updated successfully!";
} else {
echo "Error: " . $db->conn->error;
}
4. Deleting Data
$conditions = "WHERE age < 18";
if ($db->delete("users", $conditions)) {
echo "Records deleted successfully!";
} else {
echo "Error: " . $db->conn->error;
}
Step 3: Enhancing the Class
To make the class more robust, you can:
- Add Error Handling:
if (!$this->conn->query($sql)) { throw new Exception("Query Error: " . $this->conn->error); }
- Add Pagination Support:
public function selectWithLimit($table, $columns = "*", $conditions = "", $limit = 10, $offset = 0) { $sql = "SELECT $columns FROM $table $conditions LIMIT $limit OFFSET $offset"; // Same fetch logic as the select method }
- Transaction Support:
public function beginTransaction() { $this->conn->begin_transaction(); } public function commit() { $this->conn->commit(); } public function rollback() { $this->conn->rollback(); }
- Prepared Statements for Security: (For select, update, delete)
Step 4: Full Example
Here’s how you might combine everything in one usage example:
<?php
$db = new Database("localhost", "username", "password", "database");
// Insert data
$db->insert("users", ['name' => 'Alice', 'email' => 'alice@example.com', 'age' => 25]);
// Fetch data
$users = $db->select("users", "*", "WHERE age > 20 ORDER BY age DESC");
// Update data
$db->update("users", ['email' => 'updated@example.com'], "WHERE name = 'Alice'");
// Delete data
$db->delete("users", "WHERE age < 18");
// Close the connection
$db->close();
?>
This setup allows for easy and modular database operations in your PHP projects! Let me know if you need further clarification or additional features.
Comments