validating users in jquery using php

I have a users table that includes a column name called "roles". I want to select the details of the user where the column name "roles" is "admin" and show a button only admin can see

my jquery code is as below

$(document).ready(function () {
    load_comment();
    function load_comment() {// show comment function
        $.ajax({
            type: "POST",
            url: "code.php",
            data: {
                't_id' : <?php echo $_GET['id']; ?>,
                'comment_load_data': true
            },
            success: function (response) {
                $('.comment-container').html("");
                // console.log(response);
                $.each(response, function (key, value) {
                        $('.comment-container').
                            append('<div class="reply_box border p-2 mb-2">\
                            <h6 class="border-bottom d-inline">  '+value.user['username'] +' | '+value.cmt['time'] +' </h6>\
                            <p class="para"> '+value.cmt['comment'] +' </p>\
                            <button value="'+value.cmt['ID'] +'" class="badge btn-warning reply_btn">Reply</button>\
                            <button id="view" value="'+value.cmt['ID'] +'" class="badge btn-danger view_reply_btn">View Replies</button>\
                            <?php $sql = "SELECT * FROM users WHERE role = 'admin';"; $result = $con->query($sql);if ($result->num_rows > 0) {while($row = $result->fetch_assoc()) {if  ($row["role"] == "admin"){ echo "<button>Delete</button>";}}}?>\
                            <div class="ml-4 reply_section"></div>\
                            </div>\
                    ');
                });
            }
        });
    }

The sql query is working fine in PHPMyAdmin but the button is not shown when I logged in as a admin This script is included in a PHP file

Answer

Solution:

So you'll need to check if the current user is an admin. As M. Eriksson mentioned your current code will get all users with the admin role and print a delete button for each user found.

What you actually need to do is get the current users role and check if that it matches admin. Assuming the current user ID accessible somewhere in your code you could start by doing a query something like...

<?php
    // CHANGE THIS TO YOUR CURRENT USER ID
    $current_user_id = 1; // maybe get_current_user_id() ??

    $statement = $con->prepare("SELECT * FROM users WHERE id = ?");
    $statement->bind_param('i', $current_user_id);
    $statement->execute();
    
    // User specific variables
    $user = $statement->fetch_assoc();
    $is_admin = ($user['role'] ?? null) === 'admin';
?>

Once you have the above variables you can do something like...

// Create JS variables. (We print boolean values with `json_encode`).
const userIsAdmin = <?= json_encode($is_admin); ?>;
const postId = <?= (int)$_GET['id']; ?>;

(function($) {

    const $container = $('.comment-container');

    // Make ajax request.
    $.ajax({
        type: 'POST',
        url: 'code.php',
        data: {
            t_id: postId,
            comment_load_data: true
        },
        success: function (response) {

            // Empty the container, for some reason it might have contents already ??\_(??�)_/??
            $container.empty();

            // Loop through each comment.
            $.each(response, function (key, value) {

                const comment = data?.cmt;
                const author = data?.user;

                // Create a comment box.
                const $commentBox = $('<div>', {
                    class: 'reply_box border p-2 mb-2'
                }).appendTo($container);

                // Give the reply a title (and add it to the comment box).
                $('<h6>', {
                    class: 'border-bottom d-inline',
                    text: `${user['username']} | ${comment['time']}`
                }).appendTo($commentBox);

                // Print the comment (and add it to the comment box).
                $('<p>', {
                    class: 'para',
                    text: comment['comment']
                }).appendTo($commentBox);

                // Create a reply button (and add it to the comment box).
                $('<button>', {
                    class: 'badge btn-warning reply_btn',
                    value: comment['ID'],
                    type: 'button',
                    text: 'Reply'
                }).appendTo($commentBox);

                // Create a view button (and add it to the comment box).
                $('<button>', {
                    class: 'badge btn-danger view_reply_btn',
                    value: comment['ID'],
                    type: 'button',
                    text: 'View Replies'
                }).appendTo($commentBox);

                // Only create a delete button if the user is an admin.
                if (userIsAdmin) {
                    $('<button>', {
                        class: 'badge btn-danger delete_btn',
                        value: comment['ID'],
                        type: 'button',
                        text: 'Delete'
                    }).appendTo($commentBox); // (and add it to the comment box)
                }

                // Now add this empty div for something?
                $('<div>', {
                    class: 'ml-4 reply_section'
                }).appendTo($commentBox);

            });
        }
    });

    // Reply button event.
    $container.on('click', 'button.reply_btn', function(event) {
        event.preventDefault();
        const $button = $(this);
        const commentId = $button.attr('value');
        // Do something...
    });

    // View button event.
    $container.on('click', 'button.view_reply_btn', function(event) {
        event.preventDefault();
        const $button = $(this);
        const commentId = $button.attr('value');
        // Do something...
    });

    // Delete button event.
    $container.on('click', 'button.delete_btn', function(event) {
        event.preventDefault();
        const $button = $(this);
        const commentId = $button.attr('value');
        // Do something...
    });

})(jQuery);

One thing to note that you will want to double check the user is an admin on the server side when processing the delete action. Simply hiding the button client side isn't good enough.

Source