How can PHP be used to dynamically create subpages for new entries in a database without manually creating new files?
To dynamically create subpages for new entries in a database without manually creating new files, you can use PHP to generate the subpages based on the database entries. This can be achieved by retrieving the data from the database and using it to generate the content of the subpages on-the-fly.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT id, title, content FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$title = $row["title"];
$content = $row["content"];
// Create subpage dynamically
$subpage_content = "<h1>$title</h1><p>$content</p>";
file_put_contents("subpages/$id.php", $subpage_content);
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- What potential pitfalls can arise from using the rand() function in PHP for generating random numbers?
- Are there any best practices for maintaining references in multidimensional arrays when merging arrays in PHP?
- What are the advantages of transitioning from the mysql extension to mysqli or PDO in PHP, especially for beginners working on login systems?