Can inheritance be utilized when working with database operations?
Yes, inheritance can be utilized when working with database operations to create a more organized and reusable code structure. By creating a base class that handles common database operations and then extending it with specific classes for different tables or entities, you can reduce code duplication and make your code more maintainable.
class BaseDatabase {
protected $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class UsersDatabase extends BaseDatabase {
public function getUsers() {
$result = $this->query("SELECT * FROM users");
return $result->fetch_all(MYSQLI_ASSOC);
}
public function addUser($name, $email) {
$name = $this->connection->real_escape_string($name);
$email = $this->connection->real_escape_string($email);
$this->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
}
}
// Usage
$usersDb = new UsersDatabase('localhost', 'username', 'password', 'mydatabase');
$users = $usersDb->getUsers();
foreach ($users as $user) {
echo $user['name'] . ' - ' . $user['email'] . '<br>';
}
$usersDb->addUser('John Doe', 'john@example.com');
Related Questions
- What are the best practices for querying specific columns from a database table using PHP's mysql_fetch_array() function?
- What best practices should be followed when using regular expressions in PHP to extract specific data from a text?
- What are some potential pitfalls when using regular expressions in PHP for parsing data?