How can a database class in PHP simplify the process of handling database interactions and prevent common errors like SQL injections?
Using a database class in PHP can simplify the process of handling database interactions by encapsulating common database operations into reusable methods. This can help prevent common errors like SQL injections by properly sanitizing user input and using prepared statements to execute queries securely.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql, $params = array()) {
$statement = $this->connection->prepare($sql);
if ($statement) {
if (!empty($params)) {
$types = str_repeat('s', count($params));
$statement->bind_param($types, ...$params);
}
$statement->execute();
$result = $statement->get_result();
return $result->fetch_all(MYSQLI_ASSOC);
} else {
die("Error executing query: " . $this->connection->error);
}
}
public function close() {
$this->connection->close();
}
}
// Example of using the Database class
$db = new Database('localhost', 'username', 'password', 'database');
$results = $db->query("SELECT * FROM users WHERE id = ?", array(1));
$db->close();
Related Questions
- What potential problems can arise from not properly handling character escaping in PHP scripts?
- What are the limitations of using wordwrap() in PHP to handle line breaks in strings?
- How does the imagecreatefrompng function behave when loading images that were saved in a different format than the original?