What are the best practices for structuring PHP code to handle multiple database queries and display the results in a structured manner on a webpage?
When dealing with multiple database queries in PHP to display results on a webpage, it is best practice to use functions or classes to organize your code and make it more manageable. By structuring your code in a modular way, you can easily reuse and maintain it. Additionally, consider using prepared statements to prevent SQL injection attacks and improve performance.
<?php
// Function to establish database connection
function connectToDatabase() {
$host = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database';
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Function to execute a SQL query
function executeQuery($conn, $sql) {
$result = $conn->query($sql);
if ($result === false) {
die("Error executing query: " . $conn->error);
}
return $result;
}
// Example of using the functions above
$conn = connectToDatabase();
$sql = "SELECT * FROM users";
$result = executeQuery($conn, $sql);
// Display results on webpage
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
echo "Email: " . $row['email'] . "<br>";
echo "<br>";
}
} else {
echo "No results found";
}
$conn->close();
?>
Related Questions
- How can PHP be used to read data from a CSV file and transfer it to a MySQL database for a shop system?
- How do you typically start a new PHP project, especially if you are transitioning from other programming languages?
- What are the consequences of ignoring warnings and errors in PHP scripts, especially related to header functions?