How can a PHP class be structured to handle database queries and table names dynamically without strict naming conventions?
When handling database queries in a PHP class without strict naming conventions, it is important to have a flexible structure that allows for dynamic table names. One way to achieve this is by using class properties to store table names and dynamically constructing queries based on these properties. By doing so, the class can be easily adapted to work with different tables without the need for hardcoded table names throughout the code.
class DatabaseHandler {
private $tableName;
public function setTableName($tableName) {
$this->tableName = $tableName;
}
public function getAllRows() {
$query = "SELECT * FROM " . $this->tableName;
// Execute query and return results
}
public function insertRow($data) {
$columns = implode(', ', array_keys($data));
$values = "'" . implode("', '", array_values($data)) . "'";
$query = "INSERT INTO " . $this->tableName . " ($columns) VALUES ($values)";
// Execute query to insert data
}
}
// Example of how to use the DatabaseHandler class with dynamic table names
$handler = new DatabaseHandler();
$handler->setTableName('users');
$handler->getAllRows();
$handler->setTableName('products');
$handler->insertRow(['name' => 'Product A', 'price' => 10.99]);