In what way can the code structure be optimized to avoid redundant code and follow the DRY principle when querying the same table for different buttons in PHP?
When querying the same table for different buttons in PHP, the code structure can be optimized by creating a reusable function to handle the database query. This function can accept parameters to customize the query based on the button being clicked, thus avoiding redundant code and following the DRY (Don't Repeat Yourself) principle.
<?php
// Reusable function to query the database based on button clicked
function queryDatabase($button) {
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Customize query based on button clicked
if ($button === "button1") {
$sql = "SELECT * FROM table WHERE column1 = 'value1'";
} elseif ($button === "button2") {
$sql = "SELECT * FROM table WHERE column2 = 'value2'";
}
$result = $conn->query($sql);
// Handle query results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Process results
}
} else {
echo "0 results";
}
$conn->close();
}
// Call the function with the appropriate button parameter
$queryButton1 = queryDatabase("button1");
$queryButton2 = queryDatabase("button2");
?>
Keywords
Related Questions
- How can PHP be used to generate images based on user-selected styles for a stamp configurator?
- How can a PHP developer handle situations where a user forgets to log out in a system with a single user login?
- How can the file size of a PDF generated with fpdf in PHP affect printing speed, especially when sent directly to a network printer?