What are the advantages of encapsulating the database operations in a clean function in PHP?
Encapsulating database operations in a clean function in PHP helps improve code organization, readability, and maintainability. It also promotes code reusability and makes it easier to handle errors and exceptions related to database interactions.
function executeQuery($query) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($query);
$conn->close();
return $result;
}
// Example usage:
$query = "SELECT * FROM users";
$result = executeQuery($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}