How does the use of classes and methods in PHP impact the security and efficiency of handling database queries and escaping user input?
Using classes and methods in PHP can improve the security and efficiency of handling database queries and escaping user input by encapsulating functionality into reusable components. By properly structuring code with classes and methods, you can ensure that database queries are executed securely using prepared statements and user input is sanitized to prevent SQL injection attacks.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($sql, $params = []) {
$statement = $this->connection->prepare($sql);
if (!empty($params)) {
$types = str_repeat('s', count($params));
$statement->bind_param($types, ...$params);
}
$statement->execute();
return $statement->get_result();
}
public function escape($input) {
return $this->connection->real_escape_string($input);
}
}
$db = new Database('localhost', 'root', 'password', 'my_database');
$input = $db->escape($_POST['input']);
$result = $db->query("SELECT * FROM users WHERE username = ?", [$input]);