How can the mysqli database code in the PHP script be optimized to reduce redundancy and improve readability?
To reduce redundancy and improve readability in mysqli database code in a PHP script, you can create a function that handles database connections and queries. This function can be reused throughout the script to execute queries and handle errors consistently. By encapsulating the database logic in a function, you can simplify the code and make it easier to maintain.
<?php
// Function to handle database connections and queries
function executeQuery($query) {
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($query);
if (!$result) {
die("Query failed: " . $conn->error);
}
$conn->close();
return $result;
}
// Example usage of the executeQuery function
$query = "SELECT * FROM users";
$result = executeQuery($query);
// Process the query result
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
?>