How can the structure of a PHP class impact the overall functionality of a script, and what considerations should be made when designing classes for database access?
The structure of a PHP class can greatly impact the overall functionality of a script by organizing code in a logical and efficient manner. When designing classes for database access, considerations should be made for proper encapsulation, error handling, and security measures to prevent SQL injection attacks.
class DatabaseConnection {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
public function connect() {
$connection = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
return $connection;
}
public function query($sql) {
$connection = $this->connect();
$result = $connection->query($sql);
if (!$result) {
die("Query failed: " . $connection->error);
}
return $result;
}
public function escapeString($string) {
$connection = $this->connect();
return $connection->real_escape_string($string);
}
}
$database = new DatabaseConnection();
$sql = "SELECT * FROM users WHERE username = '" . $database->escapeString($username) . "'";
$result = $database->query($sql);
Related Questions
- What are the best practices for debugging PHP code, especially when encountering errors in function calls like check_mobile()?
- Is using a database a more efficient solution for handling parallel write access in PHP compared to file manipulation?
- How can the use of CASE statements in PHP MySQL queries affect the output based on different conditions?