Skip to content
PHP Logo

How can dynamic button IDs be generated and used to fetch specific data from a database in PHP?

When creating dynamic buttons that correspond to specific data entries in a database, you can generate unique IDs for each button based on the data it represents. These IDs can then be used to fetch the corresponding data from the database when the button is clicked. One way to achieve this is by embedding the data entry's unique identifier in the button's ID attribute and then using JavaScript to send an AJAX request to a PHP script that retrieves the data based on the ID.

php
<?php
// Assuming $data contains the data entries fetched from the database

foreach ($data as $entry) {
    $buttonID = "btn_" . $entry['id']; // Generate a unique ID for each button
    echo "<button id='$buttonID' class='data-button'>{$entry['name']}</button>";
}

// JavaScript to handle button click event and fetch data
echo "<script>
    document.querySelectorAll('.data-button').forEach(button => {
        button.addEventListener('click', function() {
            let entryID = this.id.split('_')[1]; // Extract the ID from the button's ID
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'fetch_data.php?id=' + entryID, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    console.log(xhr.responseText); // Handle the fetched data here
                }
            };
            xhr.send();
        });
    });
</script>";
?>