Skip to content
PHP Logo

How can PHP scripts be properly integrated into HTML pages to display dynamic content like prices from a database?

To properly integrate PHP scripts into HTML pages to display dynamic content like prices from a database, you can use PHP code within the HTML file to retrieve the data from the database and then echo it into the HTML where needed. This allows for dynamic content to be displayed based on the data stored in the database.

php
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve price from database
$sql = "SELECT price FROM products WHERE id = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $price = $row["price"];
    }
} else {
    echo "0 results";
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Price Display</title>
</head>
<body>
    <h1>Product Price: $<?php echo $price; ?></h1>
</body>
</html>