I am very, very new to PHP (Started this morning), so excuse my ignorance and lack of what could be common knowledge.
I'm working on a website that already has the functionality to take form data and store it in a MySQL database. I now want to fetch said data from the database every time a certain page is loaded, and use the same to apply some HTML divs to my page. Essentially I have 3 cards pre-defined in the source code, but I want it to add more cards to the page as soon as it loads, so long as there are rows in my MySQL table.
This is the code I'm using to partially achieve this: PHP:
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "newnotes";
$conn = new mysqli($server, $username, $password, $dbname);
$sql = "SELECT * FROM newnotesdetails";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$src = $row["src"];
$alt = $row["alt"];
$title = $row["title"];
$text = $row["text"];
$href = $row["href"];
}
}
echo $src, $alt, $title, $text, $href;
?>
Javascript:
<script type="text/javascript">
function createNewNotes() {
const src = "<?php echo $src; ?>";
const alt = "<?php echo $alt; ?>";
const title = "<?php echo $title; ?>";
const text = "<?php echo $text; ?>";
const href = "<?php echo $href; ?>";
console.log(src + alt + title + text + href);
const divelem = document.createElement("div");
divelem.classList.add("col-12", "col-md-4");
const cardelem = document.createElement("div");
cardelem.classList.add("card", "shadow", "h-100");
const area = document.querySelector(".notesblock");
divelem.appendChild(cardelem);
area.appendChild(divelem);
cardelem.innerHTML =
'<img src="' +
src +
'" alt="' +
alt +
'" class="card-img-top">' +
'<div class="card-body">' +
'<h4 class="card-title">' +
title +
"</h4>" +
'<p class="card-text">' +
text +
"</p>" +
'<a href="' +
href +
'" class="stretched-link"></a>' +
"</div>";
}
</script>
As might be evident, the issue is that PHP already finishes iterating to the last row in the table by the time my javascript code accesses the data, so I'm only adding a single card, for the last element in the MySQL table at any given time.
I'm stuck and don't know how I can iterate this to have all the rows' data successfully transfer to the js script. I'd greatly appreciate some help