[英]Push javascript array objects from mysql query
我有一個帶有以下字段的抽認卡的數據庫:
軟骨前,后
我想從它們檢索數據並將其推入帶有對象的javascript數組。
有兩個對象:正面和背面;
因此,例如,我在數據庫中有兩條記錄:
| carid | front | back |
|:-----------|------------: |:------------:|
| 1 | face1 | back1 |
| 2 | face2 | back2 |
這是我嘗試過的:
碼:
<!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>
問題在於它僅從表的第一行打印我數據。 (face1和back1)。
編輯:另一個嘗試與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);
但是,然后如何將每個數據行推送到javascript數組? 最終的填充數組應如下所示: pic
您要使用結果創建單個數組,然后使用json_encode將數據放入javascript可以輕松使用的格式。
$cards = array();
while ($stmt->fetch()) {
$cards[] = array('front' => $front, 'back' => $back);
}
-
let cards = <?php json_encode($cards); ?>;
編輯
要將正面和背面放置在它們自己的對象中,則需要創建兩個數組,然后將它們合並
$frontArr = array();
$backArr = array();
while($stmt->fetch()) {
$frontArr[] = $front;
$backArr[] = $back;
}
$cards = array($frontArr, $backArr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.