What are the best practices for structuring and organizing PHP scripts that handle the automatic generation of HTML pages from MySQL data?
When structuring and organizing PHP scripts that handle the automatic generation of HTML pages from MySQL data, it is best to separate your code into different files for better organization and readability. Use functions to encapsulate specific tasks, such as connecting to the database, querying data, and generating HTML output. Additionally, consider using a templating system or framework to further streamline the process and separate business logic from presentation.
// db_connection.php
<?php
function connectToDatabase() {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
?>
// data_query.php
<?php
function fetchDataFromDatabase($conn) {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
return $result->fetch_all(MYSQLI_ASSOC);
} else {
return [];
}
}
?>
// html_output.php
<?php
function generateHTMLTable($data) {
$html = "<table>";
foreach ($data as $row) {
$html .= "<tr>";
foreach ($row as $value) {
$html .= "<td>{$value}</td>";
}
$html .= "</tr>";
}
$html .= "</table>";
return $html;
}
?>