OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Fetching data from mysql db to display in my webpage [closed]

  • Thread starter Thread starter Jonathan Mukhobe
  • Start date Start date
J

Jonathan Mukhobe

Guest
In my system, when a student creates an account, their info is stored in mysql db. I want that once they log in, their name, course and semester are displayed on the top of my webpage but It's challenging, Can anyone help?

Below, is my php code to fetch data,the html code and the javascript

Code:
<?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['ID'])) {
    header("Location: welcome.html"); // Redirect to login page if not logged in
    exit();
}

// Connect to the database
$db = new mysqli('localhost', 'root', '', 'sys1db');

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

// Retrieve the user's information
$user_id = $_SESSION['ID'];
$query = "SELECT Name, Course, Semester FROM systable1 WHERE ID = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $user = $result->fetch_assoc();
    $name = $user['Name'];
    $course = $user['Course'];
    $semester = $user['Semester'];
} else {
    // Handle the case where user information is not found
    $name = "Guest";
    $course = "N/A";
    $semester = "N/A";
}

$stmt->close();
$db->close();

// Output the data as JSON
header('Content-Type: application/json');
echo json_encode(array(
    'Name' => $name,
    'Course' => $course,
    'Semester' => $semester
));
?>

This is my html

Code:
<!DOCTYPE HTML>
<html>
<head><title>Student Portal</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    body {
    font-family: Arial, sans-serif;
    display: grid;
    grid-template-areas: 
        "header header"
        "nav main"
        "footer footer";
    grid-template-columns: 200px 1fr;
    grid-template-rows: auto 1fr auto;
    gap: 10px;
    height: 100vh;
    margin: 0;
    padding: 0;
    background: #f4f4f4;
}

header {
    grid-area: header;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #0056b3;
    padding: 10px;
}

#student-photo, #university-logo {
    height: 150px;
}

#student-info {
    color: white;
    text-align: center;
}

nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

nav ul li a {
    display: block;
    padding: 10px;
    color: #333;
    text-decoration: none;
    transition: background-color 0.3s, color 0.3s;
}

nav ul li a:hover {
    background-color: #0056b3;
    color: white;
}

main {
    grid-area: main;
    padding: 20px;
}

aside {
    grid-area: nav;
    background: #e9ecef;
}
.slideshow-container {
    width: 100%;
    overflow: hidden;
}

.slides {
    width: 50%;
    display: none;
    transition: opacity 1s;
}
.slides.active {
    display: block;
    opacity: 1;
}

footer {
    grid-area: footer;
    text-align: center;
    padding: 10px 20px;
    background: #333;
    color: white;
}
    </style>
</head>
<body>
     <header>
        <img src="student.png" alt="Student Photo" id="student-photo">
        <div id="student-info">
            <h1>BIG PAPI UNIVERSITY</h1>
            <p id = "student-name" >Student Name</p>
            <p id="student-course">COURSE</p>
            <p id="student-semester">SEMESTER</p>
        </div>
        <img src="badge.jpg" alt="University Logo" id="university-logo">
    </header>
    <aside>
        <nav>
            <ul>
                <li><a href="#timetable">Timetable</a></li>
                <li><a href="#events">Events</a></li>
                <li><a href="#about">About Us</a></li>
                <li><a href="#library">Library</a></li>
                <li><a href="#contact">Contact Us</a></li>
                <li><a href="#feedback">Student Feedback</a></li>
                <li><a href="#email">University Email</a></li>
            </ul>
        </nav>
    </aside>
    <main>
        <section id="announcements">
            <h2>Announcements</h2>
            <p>Reminder: Midterm exams start next week!</p>
        </section>
        <section id="progress">
            <h2>Class Progress</h2>
            <p>Test scores and upcoming assignments are updated weekly.</p>
        </section>
        <section id="slideshow">
            <div class="slideshow-container">
            <h2>Our Campus</h2>
            <img src="campus.jpg" alt="Campus View" class="slides">
            <img src="library.jpg" alt="Library" class="slides">
            <img src="hall.jpg" alt="Lecture Hall" class="slides">
        </div>
         <a class="prev" onclick="moveSlide(-1)">Previous</a>
          <a class="next" onclick="moveSlide(1)">Next</a>
        </section>
    </main>
    <footer>
        <p>Contact us: <a href="mailto:[email protected]">[email protected]</a></p>
    </footer>
    <script src = "script.js">
</script>

</body>
</html>

This is the javascript

Code:
document.addEventListener('DOMContentLoaded', function() {
    // Fetch user data
    fetch('fetchdata.php')
        .then(response => response.json())
        .then(data => {
            document.getElementById('student-name').innerText = data.Name;
            document.getElementById('student-course').innerText = data.Course;
            document.getElementById('student-semester').innerText = data.Semester;
        })
        .catch(error => {
            console.error('Error fetching user data:', error);
        });

    // Slideshow functionality
    var slides = document.querySelectorAll('.slides');
    var prevBtn = document.querySelector('.prev');
    var nextBtn = document.querySelector('.next');
    var slideIndex = 1;
    var timer;

    showSlide(slideIndex);

    function moveSlide(n) {
        clearInterval(timer);
        showSlide(slideIndex += n);
        startTimer();
    }

    function showSlide(n) {
        if (n > slides.length) {slideIndex = 1}
        if (n < 1) {slideIndex = slides.length}
        for (var i = 0; i < slides.length; i++) {
            slides[i].classList.remove('active');
        }
        slides[slideIndex-1].classList.add('active');
    }

    function startTimer() {
        timer = setInterval(function() {
            moveSlide(1);
        }, 3000); // Change image every 3 seconds
    }

    startTimer();

    prevBtn.addEventListener('click', function() {
        moveSlide(-1);
    });

    nextBtn.addEventListener('click', function() {
        moveSlide(1);
    });
});

<p>In my system, when a student creates an account, their info is stored in mysql db. I want that once they log in, their name, course and semester are displayed on the top of my webpage but It's challenging, Can anyone help?</p>
<p>Below, is my php code to fetch data,the html code and the javascript</p>
<pre><code><?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['ID'])) {
header("Location: welcome.html"); // Redirect to login page if not logged in
exit();
}

// Connect to the database
$db = new mysqli('localhost', 'root', '', 'sys1db');

// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}

// Retrieve the user's information
$user_id = $_SESSION['ID'];
$query = "SELECT Name, Course, Semester FROM systable1 WHERE ID = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
$name = $user['Name'];
$course = $user['Course'];
$semester = $user['Semester'];
} else {
// Handle the case where user information is not found
$name = "Guest";
$course = "N/A";
$semester = "N/A";
}

$stmt->close();
$db->close();

// Output the data as JSON
header('Content-Type: application/json');
echo json_encode(array(
'Name' => $name,
'Course' => $course,
'Semester' => $semester
));
?>

</code></pre>
<p>This is my html</p>
<pre><code><!DOCTYPE HTML>
<html>
<head><title>Student Portal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: Arial, sans-serif;
display: grid;
grid-template-areas:
"header header"
"nav main"
"footer footer";
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
gap: 10px;
height: 100vh;
margin: 0;
padding: 0;
background: #f4f4f4;
}

header {
grid-area: header;
display: flex;
justify-content: space-between;
align-items: center;
background: #0056b3;
padding: 10px;
}

#student-photo, #university-logo {
height: 150px;
}

#student-info {
color: white;
text-align: center;
}

nav ul {
list-style: none;
padding: 0;
margin: 0;
}

nav ul li a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
transition: background-color 0.3s, color 0.3s;
}

nav ul li a:hover {
background-color: #0056b3;
color: white;
}

main {
grid-area: main;
padding: 20px;
}

aside {
grid-area: nav;
background: #e9ecef;
}
.slideshow-container {
width: 100%;
overflow: hidden;
}

.slides {
width: 50%;
display: none;
transition: opacity 1s;
}
.slides.active {
display: block;
opacity: 1;
}

footer {
grid-area: footer;
text-align: center;
padding: 10px 20px;
background: #333;
color: white;
}
</style>
</head>
<body>
<header>
<img src="student.png" alt="Student Photo" id="student-photo">
<div id="student-info">
<h1>BIG PAPI UNIVERSITY</h1>
<p id = "student-name" >Student Name</p>
<p id="student-course">COURSE</p>
<p id="student-semester">SEMESTER</p>
</div>
<img src="badge.jpg" alt="University Logo" id="university-logo">
</header>
<aside>
<nav>
<ul>
<li><a href="#timetable">Timetable</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#library">Library</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#feedback">Student Feedback</a></li>
<li><a href="#email">University Email</a></li>
</ul>
</nav>
</aside>
<main>
<section id="announcements">
<h2>Announcements</h2>
<p>Reminder: Midterm exams start next week!</p>
</section>
<section id="progress">
<h2>Class Progress</h2>
<p>Test scores and upcoming assignments are updated weekly.</p>
</section>
<section id="slideshow">
<div class="slideshow-container">
<h2>Our Campus</h2>
<img src="campus.jpg" alt="Campus View" class="slides">
<img src="library.jpg" alt="Library" class="slides">
<img src="hall.jpg" alt="Lecture Hall" class="slides">
</div>
<a class="prev" onclick="moveSlide(-1)">Previous</a>
<a class="next" onclick="moveSlide(1)">Next</a>
</section>
</main>
<footer>
<p>Contact us: <a href="mailto:[email protected]">[email protected]</a></p>
</footer>
<script src = "script.js">
</script>

</body>
</html>


</code></pre>
<p>This is the javascript</p>
<pre><code>document.addEventListener('DOMContentLoaded', function() {
// Fetch user data
fetch('fetchdata.php')
.then(response => response.json())
.then(data => {
document.getElementById('student-name').innerText = data.Name;
document.getElementById('student-course').innerText = data.Course;
document.getElementById('student-semester').innerText = data.Semester;
})
.catch(error => {
console.error('Error fetching user data:', error);
});

// Slideshow functionality
var slides = document.querySelectorAll('.slides');
var prevBtn = document.querySelector('.prev');
var nextBtn = document.querySelector('.next');
var slideIndex = 1;
var timer;

showSlide(slideIndex);

function moveSlide(n) {
clearInterval(timer);
showSlide(slideIndex += n);
startTimer();
}

function showSlide(n) {
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (var i = 0; i < slides.length; i++) {
slides.classList.remove('active');
}
slides[slideIndex-1].classList.add('active');
}

function startTimer() {
timer = setInterval(function() {
moveSlide(1);
}, 3000); // Change image every 3 seconds
}

startTimer();

prevBtn.addEventListener('click', function() {
moveSlide(-1);
});

nextBtn.addEventListener('click', function() {
moveSlide(1);
});
});
</code></pre>
 

Latest posts

Top