What are some best practices for dynamically generating buttons in PHP, especially when the button content is stored in a database?

When dynamically generating buttons in PHP where the button content is stored in a database, it is important to properly sanitize the data to prevent SQL injection attacks. Additionally, it is recommended to use prepared statements when querying the database to further protect against injection attacks. Finally, ensure that the generated buttons have unique identifiers to handle any potential conflicts.

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

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

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

// Query database for button content
$sql = "SELECT id, button_text FROM buttons";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output buttons
    while($row = $result->fetch_assoc()) {
        $buttonId = $row["id"];
        $buttonText = $row["button_text"];
        echo "<button id='button_$buttonId'>$buttonText</button>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>