In terms of PHP development, what are the advantages of separating concerns and responsibilities in code structure, such as separating database connection logic from query execution?
Separating concerns and responsibilities in code structure helps improve code maintainability, scalability, and reusability. By separating database connection logic from query execution, it becomes easier to make changes to the database connection without affecting the query execution code. It also promotes better organization and readability of the code.
// Separate database connection logic
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'example';
public function connect() {
return new mysqli($this->host, $this->username, $this->password, $this->database);
}
}
// Query execution
$db = new Database();
$conn = $db->connect();
$query = "SELECT * FROM users";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found";
}
$conn->close();
Related Questions
- How important is it for users' information to be securely stored in an SQL database for login and registration purposes?
- Are there any recent updates or changes to the Facebook API that could be affecting the functionality of retrieving events from a page?
- How can user access levels be implemented in PHP to control access to admin features?