首页 > 解决方案 > Push javascript array objects from mysql query

问题描述

I have a database with flashcards with the following fields:

cartid, front, back

I want to retrieve the data form them and push them to javascript array with objects.

There's two objects: face and back;

So, for example, I have two records in the database:

| carid      |  front       | back         |
|:-----------|------------: |:------------:|
| 1          |      face1   |     back1    |
| 2          |      face2   |    back2     |

Here's what I tried:

Code:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="caro.css">
    <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>
</head>

<body>

<div class="wrapper">
    <div class="carousel">
    </div>
    <button class="prev">Prev</button>
    <button class="next">Next</button>

</div>

<br>

<?php

include 'connection.php';
$stmt = $db->prepare("SELECT * FROM `cards`");

$stmt->bind_result($cartid, $front, $back);
$stmt->execute();


while ($stmt->fetch()) {
    ?>

    <script>
        let cards = []; //Array to store the front and the back of the flashcards
        cards.push({
            front: "<?php echo $front; ?>",
            back: "<?php echo $back; ?>"
        });

        //flash carousel
            let currentCard = 1,
            carousel = document.querySelector(".carousel"),
            next = document.querySelector(".next"),
            prev = document.querySelector(".prev");

        renderCards();

        function renderCards() {
            carousel.style.width = `${cards.length}00vw`;
            cards.map(el => {
                let div = document.createElement("div");
                div.classList.add("card");
                let front = document.createElement("div");
                front.classList.add("front");
                let back = document.createElement("div");
                back.classList.add("back");
                front.textContent = el.front;
                back.textContent = el.back;
                div.appendChild(front);
                div.appendChild(back);
                div.addEventListener("click", function (e) {
                    e.srcElement.parentNode.classList.toggle("active");
                });
                carousel.appendChild(div);
            });
        }

        next.addEventListener("click", function (e) {
            if (currentCard >= cards.length) {
                return;
            }
            currentCard++;
            cardFly();
        });

        prev.addEventListener("click", function (e) {
            if (currentCard - 1 <= 0) {
                return;
            }
            currentCard--;
            cardFly();
        });

        function cardFly() {
            carousel.style.transform = `translateX(-${currentCard - 1}00vw)`;

        }

    </script>

    <?php

} //closing while loop

?>

</body>


</html>

The problem is that it only prints me the data from the first row of the table. (face1 and back1).

Edit: Another try with json_econde

 $stmt = $db->prepare("
                 SELECT * FROM `cards`" );

        $stmt->bind_result($cartid, $front, $back);
        $stmt->execute();


            $result_array = Array();

            $result_array2 = Array();

            while ($stmt->fetch()) {

                $result_array[] = $front;

                $result_array2[] = $back;

                }
       $json_array = json_encode($result_array);

       $json_array2 = json_encode($result_array2);

But then how to push each data row to the javascript array? The final filled array should look like this: pic

标签: javascriptphpjqueryhtml

解决方案


You want to create a single array with the results, then use json_encode to put the data in a format that javascript can use easily.

$cards = array();

while ($stmt->fetch()) {
    $cards[] = array('front' => $front, 'back' => $back);
}

--

let cards = <?php json_encode($cards); ?>;

Edit

To put the front and back in their own objects, then you would need to create two arrays, and then merge them

$frontArr = array();
$backArr = array();

while($stmt->fetch()) {
   $frontArr[] = $front;
   $backArr[] = $back;
}

$cards = array($frontArr, $backArr);

推荐阅读