Is it recommended to separate database queries from HTML output in PHP development?
Separating database queries from HTML output is recommended in PHP development to improve code readability, maintainability, and security. By keeping these concerns separate, it becomes easier to make changes to the database logic without affecting the presentation layer. Additionally, separating database queries helps prevent SQL injection attacks by properly sanitizing user input before executing queries.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query the database
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
// Output HTML
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td></tr>";
}
echo "</table>";
// Close connection
$conn->close();
?>