Page 516 - Computer_Science_F5
P. 516
By embedding PHP code within HTML and CSS, you can create dynamic content
that can be updated and displayed on the webpage based on user interactions or
backend data.
An example of how to embed PHP in HTML and CSS to create dynamic content
FOR ONLINE READING ONLY
using an imaginary “farming” database with a table called “crops” containing Chapter Eight: Databases and Database Management Systems
columns like “image_url”, “description”, “crop_name”, and “harvest_season”. The
PHP code connects to the database, fetches the data, and then the HTML file embeds
the PHP code to display the dynamic content in a gallery format using CSS. It is as
follows:
First, create a PHP file to connect to the database and fetch data as shown in Program
Example 8.4:
Program Example 8.4:
PHP program to connect to the database and fetch data
<?php
// Connect to the farming database
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “farming_database”;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
// Fetch data from the farming database
$sql = “SELECT * FROM crops”;
$result = $conn->query($sql);
// Close the database connection
$conn->close();
?>
507
Student’s Book Form Five
Computer Science Form 5.indd 507 23/07/2024 12:35

