In what ways can PHP developers improve their code structure and readability by utilizing object-oriented programming (OOP) principles in mysqli usage?
By utilizing object-oriented programming (OOP) principles in mysqli usage, PHP developers can improve their code structure and readability by encapsulating database operations within classes, making the code more modular and easier to maintain. This approach also promotes code reusability and allows for better error handling and abstraction of database interactions.
// Example of using OOP principles in mysqli usage
class Database {
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->conn = new mysqli($host, $username, $password, $dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function close() {
$this->conn->close();
}
}
// Example of using the Database class
$db = new Database('localhost', 'username', 'password', 'database_name');
$result = $db->query("SELECT * FROM users");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
$db->close();
Related Questions
- What are the best practices for handling form submissions and preventing duplicate submissions in PHP?
- How can the PHP script be modified to ensure that the page parameters are not ignored and the correct pages are displayed?
- Are there any specific PHP functions or libraries that can assist in displaying subpages of a website?