How can PHP be used effectively in creating dynamic websites?

PHP can be used effectively in creating dynamic websites by embedding PHP code within HTML to create dynamic content, interact with databases, handle form submissions, and more. By utilizing PHP's server-side scripting capabilities, developers can create websites that respond to user input and deliver personalized content.

<?php
// Connect to a database
$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);
}

// Retrieve data from the database
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>