What improvements can be made to simplify and optimize the PHP code for SELECT queries to avoid repetitive output issues?
When dealing with repetitive output issues in PHP SELECT queries, one way to simplify and optimize the code is to use a function to handle the database connection and query execution. By encapsulating the database operations within a function, you can avoid code duplication and make it easier to manage and maintain the code.
<?php
// Function to handle database connection and query execution
function executeQuery($query) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$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 of the executeQuery function
$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";
}
?>
Related Questions
- How can SQL Injections be prevented in PHP when querying a database?
- How can performance issues be mitigated when querying and selecting data from a table with multiple selections stored as strings?
- Are there any recommended PHP libraries or frameworks that can simplify the process of implementing file upload and email functionality on a website?