What are the fundamental PHP OOP concepts that should be understood before attempting to implement complex database interactions?
Before attempting complex database interactions in PHP, it is essential to understand fundamental Object-Oriented Programming (OOP) concepts such as classes, objects, inheritance, encapsulation, and polymorphism. These concepts will help you organize your code, create reusable components, and maintain a clear structure for interacting with databases.
class DatabaseConnection {
private $servername;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($servername, $username, $password, $dbname) {
$this->servername = $servername;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
$result = $this->conn->query($sql);
return $result;
}
public function closeConnection() {
$this->conn->close();
}
}
// Example usage
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$db = new DatabaseConnection($servername, $username, $password, $dbname);
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
$db->closeConnection();