Извлечь user_id из таблицы MYSQL и установить атрибуты HTML (img src, ссылка href, тег h3) с помощью Jquery

0

Я пытаюсь получить user_id и имя пользователя из таблицы с помощью запроса MySQL.

Всего в моей таблице 12 пользователей/строк данных, и я хочу отображать только 6 результатов одновременно.

Цель состоит в том, чтобы отобразить изображение профиля пользователя путем объединения каталога, в котором хранится изображение, с уникальным user_id пользователя:

data/profiles/users/profile_img/{users_id}/main.jpg

Затем изображения вращаются (случайным образом) каждые 5 секунд, используя JQUERY для обновления атрибута img src.

Кроме того, я устанавливаю ссылку href с user_id пользователей, чтобы пользователь мог щелкнуть изображение и перейти в профиль этого пользователя.

Это все отлично работает. Однако я также хочу отобразить имя пользователя в атрибуте html <h3> для каждого элемента.

Кажется, мне трудно этого достичь. Вместо того, чтобы получать одно имя пользователя для каждого элемента, я получаю все имена пользователей для каждого элемента.

Пожалуйста, может кто-нибудь показать мне, где я иду не так?

Код:

<?php $result = $conn->query("SELECT  * FROM user_data, user_locations WHERE user_data.user_id = user_locations.user_id AND user_data.advert_type = 'Deluxe' AND user_data.advert_status = 'Active' ");
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { 
        $p_id = $row['user_id'];
        $name = $row['first_name'] . ' ' . $row['last_name'];

        $new_array[] = $p_id;
        $new_array2[] = $name;
    }
}

echo '<script>';
echo 'var imagesArray = ' . json_encode($new_array) . ';';
echo 'var imagesArray2 = ' . json_encode($new_array2) . ';';
echo '</script>';            
?> 

<script>
//Good shuffle algorithm: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    function shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    function changeComponent() {
        // store image query in a variable
        var $allImages = $(".deluxe_ad_img");
        // take X random IDs by shuffling the list and taking the first X
        // (slice total dynamically, in case you ever need more or less than exactly 6)
        var randomIDs = shuffle(imagesArray).slice(0, $allImages.length);
        var randomIDs2 = shuffle(imagesArray2).slice(0, $allImages.length);

        // iterate over each image, using the index of the iteration.
        $allImages.each(function (idx) {
            $(this).attr('src', 'data/profiles/users/profile_img/' + randomIDs[idx] + '/main.jpg');
            $(this).parent(".deluxe_component_link").attr('href', 'profile.php?p_id=' + randomIDs[idx]);

            $("h3.deluxe_title").text(randomIDs2);
        });
    }
    $(document).ready(function () {

        changeComponent();
        setInterval(function() {
            changeComponent();
        }, 10000);
    })
</script>





<div class="deluxe_listing_container">
<?php 
//Echo out results
echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';


?>

</div>

1 ответ

1
Лучший ответ

Пожалуйста, попробуйте ниже, и прочитайте все комментарии, чтобы вы поняли изменения.

<?php $result = $conn->query("SELECT  * FROM user_data, user_locations WHERE user_data.user_id = user_locations.user_id AND user_data.advert_type = 'Deluxe' AND user_data.advert_status = 'Active' ");
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { 
        $p_id = $row['user_id'];
        $name = $row['first_name'] . ' ' . $row['last_name'];

        // have 1 array, but each element is an array containing both name and id. this will keep the data together even when you shuffle later
        $new_array[] =  array('p_id' => $p_id, 'name' => $name);
    }
}

echo '<script>';
echo 'var imagesArray = ' . json_encode($new_array) . ';';
echo '</script>';            
?> 

<script>
//Good shuffle algorithm: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    function shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    function changeComponent() {
        // get all the component containers
        var $allComponents = $(".deluxe_component");
        // take X random people by shuffling the list and taking the first X
        // (slice by .length dynamically, in case you ever need more or less than exactly 6)
        var randomPeople = shuffle(imagesArray).slice(0, $allComponents.length);

        // iterate over each image, using the index of the iteration.
        $allComponents.each(function (idx) {
            // find the image element in this component and add the src, using the 'p_id' field of this particular randomPeople[idx]
            $(this).find('.deluxe_ad_img').attr('src', 'data/profiles/users/profile_img/' + randomPeople[idx]['p_id'] + '/main.jpg');
            // find the link element in this component and add the href, using the 'p_id' field of this particular randomPeople[idx]
            $(this).find(".deluxe_component_link").attr('href', 'profile.php?p_id=' + randomPeople[idx]['p_id']);
            // find the h3 element in this component and add the name, using the 'name' field of this particular randomPeople[idx]
            $(this).find("h3.deluxe_title").text(randomPeople[idx]['name']);
        });
    }
    $(document).ready(function () {

        changeComponent();
        setInterval(function() {
            changeComponent();
        }, 10000);
    })
</script>





<div class="deluxe_listing_container">
<?php 
//Echo out results
echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';

echo '<div class="deluxe_component"><a href="" class="deluxe_component_link">';
echo '<img class="deluxe_ad_img" src="" height="auto" width="auto" />';
echo '<h3 class="deluxe_title"></h3><p class="deluxe_subtitle"></p></a></div>';


?>

</div>
  • 0
    отлично. работает отлично

Ещё вопросы

Сообщество Overcoder
Наверх
Меню