Establishing a database connection:
- class Database { private $host = "localhost"; private $db_name = "mydatabase"; private $username = "root"; private $password = ""; public $conn; public function getConnection() { $this->conn = null; try { $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $exception) { echo "Connection error: " . $exception->getMessage(); } return $this->conn; } }
- Creating a class for CRUD operations:
- class Crud { private $conn; private $table_name = "mytable"; public function __construct($db) { $this->conn = $db; } // CREATE public function create($name, $email, $phone) { $query = "INSERT INTO " . $this->table_name . " (name, email, phone) VALUES (:name, :email, :phone)"; $stmt = $this->conn->prepare($query); $stmt->bindParam(":name", $name); $stmt->bindParam(":email", $email); $stmt->bindParam(":phone", $phone); if($stmt->execute()) { return true; } else { return false; } } // READ public function read() { $query = "SELECT * FROM " . $this->table_name; $stmt = $this->conn->prepare($query); $stmt->execute(); return $stmt; } // UPDATE public function update($id, $name, $email, $phone) { $query = "UPDATE " . $this->table_name . " SET name=:name, email=:email, phone=:phone WHERE id=:id"; $stmt = $this->conn->prepare($query); $stmt->bindParam(":id", $id); $stmt->bindParam(":name", $name); $stmt->bindParam(":email", $email); $stmt->bindParam(":phone", $phone); if($stmt->execute()) { return true; } else { return false; } } // DELETE public function delete($id) { $query = "DELETE FROM " . $this->table_name . " WHERE id=:id"; $stmt = $this->conn->prepare($query); $stmt->bindParam(":id", $id); if($stmt->execute()) { return true; } else { return false; } } }
- Using the above classes for CRUD operations:
- // include database and object files include_once 'config/database.php'; include_once 'objects/crud.php'; // instantiate database and product object $database = new Database(); $db = $database->getConnection(); $crud = new Crud($db); // CREATE if(isset($_POST['create'])) { $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; if($crud->create($name, $email, $phone)) { echo "Record created successfully."; } else { echo "Error: Record creation failed."; } } // READ $stmt