What are the best practices for dynamically generating content with PHP and MySQL without compromising security?

When dynamically generating content with PHP and MySQL, it is important to sanitize user input to prevent SQL injection attacks and cross-site scripting vulnerabilities. One way to do this is by using prepared statements and parameterized queries to securely interact with the database. Additionally, validating and escaping user input before displaying it on the webpage can help prevent malicious code execution.

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Sanitize user input using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the query
$stmt->execute();

// Get the results
$result = $stmt->get_result();

// Display the data
while ($row = $result->fetch_assoc()) {
    echo "Username: " . htmlspecialchars($row['username']) . "<br>";
    echo "Email: " . htmlspecialchars($row['email']) . "<br>";
}

// Close the connection
$stmt->close();
$conn->close();