
Olumide
Members-
Posts
135 -
Joined
-
Last visited
-
Days Won
3
Everything posted by Olumide
-
The fee is not constant, it do change, and for instance, a student who lives in hostel (Boarder) might decide he want to be coming from home as Day student, and a Day student can even decide he want to stay in hostel for a week maybe for a purpose known to him, and this do cause confusion if there is fixed price. Also, some parents might decide they want to pay less on any of the fee either IGCSE, Sports or anything. That is why I think entering the fee manually could be okay to handle such scenario. Some students are on scholarship where tuition will be free, but they will pay for other expenses and some on free feeding, and so on. And School fee may change anytime.
-
Thanks @BarandCan you please give me more hints on this?
-
total_fee_payable is still not calculating well but calculated_total_fee calculated well as required. I want this calculated as: total_fee_payable = (fee_amount + total_fee_from_items) - (total_fee_from_items + discount_amount) I have tried many approach but not working, it is not adding the amounts in the items_table to the total_fee_payable in the invoices table. From the sample query below: From items_table: invoice_id 118 should be added to the invoices id total_fee_payable CREATE TABLE `invoices` ( `id` int(11) NOT NULL, `student_id` int(11) NOT NULL, `semester_id` int(11) NOT NULL, `student_name` varchar(255) NOT NULL, `current_class_id` varchar(255) DEFAULT NULL, `fee_description` varchar(255) NOT NULL, `fee_amount` decimal(10,2) NOT NULL, `less_fee_description` varchar(255) DEFAULT NULL, `less_fee_amount` decimal(10,2) DEFAULT NULL, `discount_amount` decimal(10,2) DEFAULT NULL, `total_fee_payable` decimal(10,2) NOT NULL, `invoice_number` varchar(50) NOT NULL, `status` enum('PAID','PENDING') DEFAULT 'PENDING', `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -- Dumping data for table `invoices` -- INSERT INTO `invoices` (`id`, `student_id`, `semester_id`, `student_name`, `current_class_id`, `fee_description`, `fee_amount`, `less_fee_description`, `less_fee_amount`, `discount_amount`, `total_fee_payable`, `invoice_number`, `status`, `created_at`, `updated_at`) VALUES (118, 678, 16, 'AU', 'Year 11', 'school fee ', '50000.00', 'hg', '1000.00', '1000.00', '48000.00', 'B/2024/67982', 'PENDING', '2024-02-03 00:12:06', '2024-02-03 00:12:06'); -- -- Triggers `invoices` -- DELIMITER $$ CREATE TRIGGER `calculate_total_fee_payable_update` BEFORE UPDATE ON `invoices` FOR EACH ROW BEGIN SET NEW.total_fee_payable = ( SELECT COALESCE(SUM(fee_amount), 0) FROM items_table WHERE invoice_id = NEW.id ) + NEW.fee_amount - COALESCE((NEW.less_fee_amount + NEW.discount_amount), 0); END $$ DELIMITER ; ALTER TABLE `invoices` ADD PRIMARY KEY (`id`), ADD KEY `semester_id` (`semester_id`), ADD KEY `fk_invoices_student` (`student_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `invoices` -- ALTER TABLE `invoices` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=119; -- -- Constraints for dumped tables -- -- -- Constraints for table `invoices` -- ALTER TABLE `invoices` ADD CONSTRAINT `fk_invoices_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`), ADD CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`semester_id`) REFERENCES `semester` (`id`); COMMIT; CREATE TABLE `items_table` ( `id` int(11) NOT NULL, `invoice_id` int(11) NOT NULL, `fee_description` varchar(255) NOT NULL, `fee_amount` decimal(10,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; INSERT INTO `items_table` (`id`, `invoice_id`, `fee_description`, `fee_amount`) VALUES (16, 118, 'sports', '5000.00'), (17, 118, 'club', '5000.00'); ALTER TABLE `items_table` ADD PRIMARY KEY (`id`), ADD KEY `fk_items_invoice` (`invoice_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `items_table` -- ALTER TABLE `items_table` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- Constraints for dumped tables -- -- -- Constraints for table `items_table` -- ALTER TABLE `items_table` ADD CONSTRAINT `fk_items_invoice` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`); COMMIT;
-
Fixing Issues with PHP, AJAX, and MySQL Data Insertion
Olumide replied to Olumide's topic in PHP Coding Help
I realized my mistake. You elders are all amazing. I don't know which one I should marked as solutions but you all did very excellent and expedite my problem to be solved. However, I am still working on it as this is just a section and when I am finally done with this, I have a vital question to ask on PHP as someone told me when I went for an interview that in the next two years, PHP will be outdated and not sellable in the market again. error_reporting(E_ALL); ini_set('display_errors', 1); // Check if the form data is set if ( isset($_POST['semesterId']) && isset($_POST['studentName']) && isset($_POST['feeDescription']) && isset($_POST['feeAmount']) && isset($_POST['lessFeeDescription']) && isset($_POST['lessFeeAmount']) && isset($_POST['discountAmount']) && isset($_POST['invoiceNumber']) //I think the problem is adding the grandTotal variable here ) { // Get form data $semesterId = $_POST['semesterId']; $studentName = $_POST['studentName']; $feeDescription = $_POST['feeDescription']; $feeAmount = $_POST['feeAmount']; $lessFeeDescription = $_POST['lessFeeDescription']; $lessFeeAmount = $_POST['lessFeeAmount']; $discountAmount = $_POST['discountAmount']; $invoiceNumber = $_POST['invoiceNumber']; // Calculate grand total $grandTotal = $feeAmount - ($lessFeeAmount + $discountAmount); // Additional validation if (empty($_POST['studentName']) || empty($_POST['feeDescription']) || empty($_POST['feeAmount'])) { header('HTTP/1.1 400 Bad Request'); echo 'Invalid form data. Please fill out all required fields.'; exit; } try { $query = "INSERT INTO invoices (semester_id, student_name, fee_description, fee_amount, less_fee_description, less_fee_amount, discount_amount, invoice_number, total_fee_payable) VALUES (:semesterId, :studentName, :feeDescription, :feeAmount, :lessFeeDescription, :lessFeeAmount, :discountAmount, :invoiceNumber, :totalFeePayable)"; // Prepare the query $stmt = $pdo->prepare($query); // Bind parameters $stmt->bindParam(':semesterId', $semesterId, PDO::PARAM_INT); $stmt->bindParam(':studentName', $studentName, PDO::PARAM_STR); $stmt->bindParam(':feeDescription', $feeDescription, PDO::PARAM_STR); $stmt->bindParam(':feeAmount', $feeAmount, PDO::PARAM_STR); $stmt->bindParam(':lessFeeDescription', $lessFeeDescription, PDO::PARAM_STR); $stmt->bindParam(':lessFeeAmount', $lessFeeAmount, PDO::PARAM_STR); $stmt->bindParam(':discountAmount', $discountAmount, PDO::PARAM_STR); $stmt->bindParam(':invoiceNumber', $invoiceNumber, PDO::PARAM_STR); $stmt->bindParam(':totalFeePayable', $grandTotal, PDO::PARAM_STR); // Bind grandTotal to the total_fee_payable column -
Fixing Issues with PHP, AJAX, and MySQL Data Insertion
Olumide replied to Olumide's topic in PHP Coding Help
I am on it right now, could you believe I only modified the save_invoice.php script and got working, but I have removed all the calculations in javascript and still not working until now, but I want to retrace my steps again. You guys (no, I won't call you guys, but elders) are amazing and wonderful family. I am still on it, and will surely be here when there is hurdles again. Thanks for now. -
Fixing Issues with PHP, AJAX, and MySQL Data Insertion
Olumide replied to Olumide's topic in PHP Coding Help
-
Fixing Issues with PHP, AJAX, and MySQL Data Insertion
Olumide replied to Olumide's topic in PHP Coding Help
I will try to add the echo and see the output. -
Fixing Issues with PHP, AJAX, and MySQL Data Insertion
Olumide replied to Olumide's topic in PHP Coding Help
Hmmm, this is very deep, I am not an expert in programming but learn everyday. The script work fine before not until I wanted to be inserting the grandTotal under fee_total_payable. And I have comment out the grandTotal again from all my code but still stopped working. From the console network tab, attached is the picture -
I have this html form which worked, but I added grandTotal to populate its column "total_fee_payable" in the table. When I added this, I altered the javascript and php code to insert the data into the database. Suddenly, it stopped working and when I checked the console log, it shows data saved successfully. What could be the problem please? Here is part of my html form <div id="student-details" class="w3-margin-top w3-margin-bottom"> <h2>Student Details</h2> <!-- Custom label and input container --> <div class="w3-row-padding"> <div class="w3-half w3-padding"> <label for="student-name">Name:</label> <input type="text" id="student-name" name="studentName" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="current-class">Current Class:</label> <input type="text" id="current-class" name="currentClass" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="selected-semester">Selected Semester:</label> <input type="text" id="selected-semester" name="selectedSemester" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="invoice-number">Invoice Number:</label> <input type="text" id="invoice-number" name="invoiceNumber" class="w3-input w3-border" disabled> </div> <div class="w3-half w3-padding"> <label for="item">Fee Description:</label> <input type="text" id="item" name="feeDescription" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Amount:</label> <input type="number" id="price" name="feeAmount" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="lessFee">Enter Less Fee Description:</label> <input type="text" id="fee_description" name="less_fee_description" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="priceAmount">Amount:</label> <input type="number" id="fee_amount" name="less_fee_amount" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Discount Amount:</label> <input type="number" id="discount_amount" name="discount_amount" class="w3-input w3-border" autocomplete="off"> </div> </div> </div> <h2 class="w3-margin-bottom">Analysis</h2> <div class="w3-responsive"> <table class="w3-table w3-hoverable w3-bordered w3-striped" id="order-item-tbl"> <tfoot> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Sub-Total</th> <th class="bg-transparent w3-border w3-right-align" id="subTotalText">0</th> </tr> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Grand Total</th> <th class="bg-transparent w3-border w3-right-align" id="grandTotal" name="grandTotal">0</th> </tr> </tfoot> </table> </div><br> <button type="button" id="order-form-submit" class="w3-button w3-blue w3-block"><i class="far fa-plus-square"> </i> Add Invoice</button> </div> Here is the javascript // Function to update the grand total based on the formula function updateGrandTotal() { // Get values from the form var price = parseFloat(document.getElementById('price').value) || 0; var feeAmount = parseFloat(document.getElementById('fee_amount').value) || 0; var discountAmount = parseFloat(document.getElementById('discount_amount').value) || 0; // Calculate grand total var grandTotal = price - (feeAmount + discountAmount); // Update the grand total element document.getElementById('grandTotal').textContent = grandTotal.toFixed(2); } // Attach the update function to input events document.getElementById('price').addEventListener('input', updateGrandTotal); document.getElementById('fee_amount').addEventListener('input', updateGrandTotal); document.getElementById('discount_amount').addEventListener('input', updateGrandTotal); // Function to save invoice data function saveInvoiceData() { var semesterId = $('#semester').val(); var studentName = $('#student-name').val(); var feeDescription = $('#item').val(); var feeAmount = $('#price').val(); var lessFeeDescription = $('#fee_description').val(); var lessFeeAmount = $('#fee_amount').val(); var discountAmount = $('#discount_amount').val(); //var grandTotal = $('#grandTotal').val(); var invoiceNumber = $('#invoice-number').val(); // Make an AJAX request to save invoice data $.ajax({ url: 'invoice.php', method: 'POST', data: { semesterId: semesterId, studentName: studentName, feeDescription: feeDescription, feeAmount: feeAmount, lessFeeDescription: lessFeeDescription, lessFeeAmount: lessFeeAmount, discountAmount: discountAmount, //grandTotal: grandTotal, invoiceNumber: invoiceNumber }, success: function (response) { // Handle success response if needed console.log('Invoice data saved successfully.'); }, error: function (error) { console.error('Error:', error); } }); } // Bind the function to "Save" button $('#order-form-submit').on('click', function () { saveInvoiceData(); }); }); Here is the invoice.php // Check if the form data is set if ( isset($_POST['semesterId']) && isset($_POST['studentName']) && isset($_POST['feeDescription']) && isset($_POST['feeAmount']) && isset($_POST['lessFeeDescription']) && isset($_POST['lessFeeAmount']) && isset($_POST['discountAmount'])&& //isset($_POST['grandTotal'])&& isset($_POST['invoiceNumber']) ) { // Get form data $semesterId = $_POST['semesterId']; $studentName = $_POST['studentName']; $feeDescription = $_POST['feeDescription']; $feeAmount = $_POST['feeAmount']; $lessFeeDescription = $_POST['lessFeeDescription']; $lessFeeAmount = $_POST['lessFeeAmount']; $discountAmount = $_POST['discountAmount']; //$grandTotal = floatval($_POST['grandTotal']); $invoiceNumber = $_POST['invoiceNumber']; // Additional validation if (empty($_POST['studentName']) || empty($_POST['feeDescription']) || empty($_POST['feeAmount'])) { header('HTTP/1.1 400 Bad Request'); echo 'Invalid form data. Please fill out all required fields.'; exit; } try { $query = "INSERT INTO invos (semester_id, student_name, fee_description, fee_amount, less_fee_description, less_fee_amount, discount_amount, invoice_number) VALUES (:semesterId, :studentName, :feeDescription, :feeAmount, :lessFeeDescription, :lessFeeAmount, :discountAmount, :invoiceNumber)"; // Prepare the query $stmt = $pdo->prepare($query); // Bind parameters $stmt->bindParam(':semesterId', $semesterId, PDO::PARAM_INT); $stmt->bindParam(':studentName', $studentName, PDO::PARAM_STR); $stmt->bindParam(':feeDescription', $feeDescription, PDO::PARAM_STR); $stmt->bindParam(':feeAmount', $feeAmount, PDO::PARAM_STR); $stmt->bindParam(':lessFeeDescription', $lessFeeDescription, PDO::PARAM_STR); $stmt->bindParam(':lessFeeAmount', $lessFeeAmount, PDO::PARAM_STR); $stmt->bindParam(':discountAmount', $discountAmount, PDO::PARAM_STR); //$stmt->bindParam(':grandTotal', $grandTotal, PDO::PARAM_STR); $stmt->bindParam(':invoiceNumber', $invoiceNumber, PDO::PARAM_STR); try { // ... // Output the executed query for debugging echo $stmt->queryString; // Execute the query $stmt->execute(); $rowCount = $stmt->rowCount(); if ($rowCount > 0) { echo 'Invoice data saved successfully.'; } else { echo 'No rows affected. Check for errors.'; } } catch (PDOException $e) { // Handle database errors echo 'Error: ' . $e->getMessage(); }
-
After using the debugger by add console log, I still don't noticed where the issue is. And you also please tell me the anomalies in my html div tags? $(document).ready(function () { const orderItemTbl = $('#order-item-tbl'); const addOrderBtn = $('#add-order-btn'); const lessTotalText = $('#lessTotal'); const subTotalText = $('#subTotalText'); let totalLessAmount = 0; let totalPriceForFeeDescriptions = 0; $(addOrderBtn).click(function (e) { e.preventDefault(); addItem(); }); function addItem() { var item = $('#item').val(); var price = $('#price').val(); var less = $('#less').val(); var lessAmount = $('#less_amount').val(); // Validate input fields if (item === '' || price === '' || price < 1) { return false; } price = parseFloat(price).toFixed(2); // two decimal places var tr = createRow(item, price); // Check if less and lessAmount are provided if (less !== '' && lessAmount !== '') { var tr2 = createRow(less, lessAmount); orderItemTbl.find('tbody').append(tr, tr2); // Update total less amount totalLessAmount += parseFloat(lessAmount); console.log("totalLessAmount after adding:", totalLessAmount); } else { orderItemTbl.find('tbody').append(tr); // Update total price for fee descriptions totalPriceForFeeDescriptions += parseFloat(price); console.log("totalPriceForFeeDescriptions after adding:", totalPriceForFeeDescriptions); } orderItemTbl.find('tbody tr.noData').hide(); // Clear input fields after adding an item clearInputFields(); // Update subtotal updateSubTotal(); // Update total less amount updateTotalLessAmount(); } function createRow(description, amount) { var tr = $('<tr>'); var removeBtn = $('<button type="button" class="remove-item w3-button w3-red w3-round w3-tiny"><i class="fas fa-times"></i></button>'); tr.append('<td class="w3-center w3-border"></td>'); tr.append(`<td class="w3-border">${description}</td>`); tr.append(`<td class="w3-right-align w3-border numeric">${parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</td>`); tr.find('td:first-child').append(removeBtn); removeBtn.click(function () { if (confirm('Are you sure to remove this item?')) { tr.remove(); clearInputFields(); if (orderItemTbl.find('tbody tr').length <= 1) { orderItemTbl.find('tbody tr.noData').show(); } if (amount !== '' && parseFloat(amount) > 0) { totalLessAmount -= parseFloat(amount); console.log("totalLessAmount after removing:", totalLessAmount); } updateSubTotal(); updateTotalLessAmount(); } }); return tr; } function clearInputFields() { $('#item').val(''); $('#price').val(''); $('#less').val(''); $('#less_amount').val(''); } function updateSubTotal() { var subTotal = totalPriceForFeeDescriptions - totalLessAmount; console.log("totalPriceForFeeDescriptions:", totalPriceForFeeDescriptions); console.log("totalLessAmount:", totalLessAmount); subTotalText.text(subTotal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } function updateTotalLessAmount() { lessTotalText.text(totalLessAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } }); Attached picture
-
Hi, I am working on this script for invoice generation, from the image attached, is the input forms at left hand side, when the add order button is clicked, it add the fee description, amount, less fee description and amount less to the fee list as shown in the right hand side of the image. In the table in the right hand, Total less item(s) will sum all the amount less), sub-total will sum all the amount and subtract it from the total less. I still have to do discount and grandtotal but I had challenges with the sub-total, giving me the same value with the Total Less Amount. Please, the experts in the house who always rescue us from our downfall should please help me address this query. Here is the html form <div class="w3-half w3-padding"> <label for="item">Fee Description:</label> <input type="text" id="item" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="price">Amount:</label> <input type="number" id="price" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="less">Less Fee Description:</label> <input type="text" id="less" class="w3-input w3-border" autocomplete="off"> </div> <div class="w3-half w3-padding"> <label for="less_amount">Amount Less:</label> <input type="number" id="less_amount" class="w3-input w3-border" autocomplete="off"> </div> </div></div> <button type="button" id="add-order-btn" class="w3-button w3-blue w3-block"><i class="far fa-plus-square"> </i> Add Order</button> </div> <!-- Fee List Section --> <div class="w3-half w3-padding w3-form-container"> <h2 class="w3-margin-bottom">Fee List</h2> <div id="fee-list-content"> <!-- testing --> <div class="w3-card w3-round w3-margin card-body"> <div class="w3-container w3-padding"> <div class="w3-responsive"> <table class="w3-table w3-hoverable w3-bordered w3-striped" id="order-item-tbl"> <colgroup> <col width="5%"> <col width="70%"> <col width="20%"> </colgroup> <thead> <tr class="bg-gradient bg-dark-subtle"> <th class="bg-transparent w3-center w3-border"></th> <th class="bg-transparent w3-center w3-border">Fee Description</th> <th class="bg-transparent w3-center w3-border">Price</th> </tr> </thead> <tbody> <tr class="noData"> <th class="w3-center w3-border" colspan="3">No Item Listed Yet</th> </tr> </tbody> <tfoot> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Total Less Item(s)</th> <th class="bg-transparent w3-border w3-right-align" id="lessTotal">0</th> </tr> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Sub-Total</th> <th class="bg-transparent w3-border w3-right-align" id="subTotalText">0</th> </tr> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Discount Amount</th> <th class="bg-transparent w3-border"> <input type="number" class="w3-input w3-small w3-round w3-right-align" step="any" name="discount_amount" id="discount_amount" min="0" max="1000000" value="0"> </th> </tr> <tr class="bg-gradient bg-dark-subtle bg-opacity-50"> <th class="bg-transparent w3-center w3-border" colspan="2">Grand Total</th> <th class="bg-transparent w3-border w3-right-align" id="grandTotalText">0</th> </tr> </tfoot> </table> Here is my javascript //<script> $(document).ready(function () { const orderItemTbl = $('#order-item-tbl'); const addOrderBtn = $('#add-order-btn'); const lessTotalText = $('#lessTotal'); const subTotalText = $('#subTotalText'); let totalLessAmount = 0; let totalPriceForFeeDescriptions = 0; addOrderBtn.click(function (e) { e.preventDefault(); addItem(); }); function addItem() { var item = $('#item').val(); var price = $('#price').val(); var less = $('#less').val(); var lessAmount = $('#less_amount').val(); // Validate input fields if (item === '' || price === '' || price < 1) { return false; } price = parseFloat(price).toFixed(2); // two decimal places var tr = createRow(item, price); // Check if less and lessAmount are provided if (less !== '' && lessAmount !== '') { var tr2 = createRow(less, lessAmount); orderItemTbl.find('tbody').append(tr, tr2); // Update total less amount totalLessAmount += parseFloat(lessAmount); } else { orderItemTbl.find('tbody').append(tr); // Update total price for fee descriptions totalPriceForFeeDescriptions += parseFloat(price); } orderItemTbl.find('tbody tr.noData').hide(); // Clear input fields after adding an item clearInputFields(); // Update subtotal updateSubTotal(); // Update total less amount updateTotalLessAmount(); } function createRow(description, amount) { var tr = $('<tr>'); var removeBtn = $('<button type="button" class="remove-item w3-button w3-red w3-round w3-tiny"><i class="fas fa-times"></i></button>'); tr.append('<td class="w3-center w3-border"></td>'); tr.append(`<td class="w3-border">${description}</td>`); tr.append(`<td class="w3-right-align w3-border numeric">${parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</td>`); tr.find('td:first-child').append(removeBtn); removeBtn.click(function () { if (confirm('Are you sure to remove this item?')) { tr.remove(); clearInputFields(); if (orderItemTbl.find('tbody tr').length <= 1) { orderItemTbl.find('tbody tr.noData').show(); } if (amount !== '' && parseFloat(amount) > 0) { totalLessAmount -= parseFloat(amount); } updateSubTotal(); updateTotalLessAmount(); } }); return tr; } function clearInputFields() { $('#item').val(''); $('#price').val(''); $('#less').val(''); $('#less_amount').val(''); } function updateSubTotal() { var subTotal = totalPriceForFeeDescriptions - totalLessAmount; subTotalText.text(subTotal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } function updateTotalLessAmount() { lessTotalText.text(totalLessAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')); } });
-
Oh! thanks, that was a mistake, I have corrected it and also modified the javascript but still getting this json error: Selected Year: 7 index.php:105 Current Semester: 2nd Term 2023/2024 index.php:136 Error fetching students: SyntaxError: Unexpected token '<', " <br /> <b>"... is not valid JSON Here is my modified javascript: <script> function updateStudentNames() { var selectedYear = document.getElementById("year").value; var currentSemester = document.getElementById("semester").value; // Get the current semester value console.log("Selected Year:", selectedYear); console.log("Current Semester:", currentSemester); var studentSelect = document.getElementById("student"); // Clear previous options studentSelect.innerHTML = ""; // Fetch and add new options based on the selected year and current semester if (selectedYear !== "") { fetch(`class_year.php?year=${selectedYear}&semester=${currentSemester}`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log("Fetched Data:", data); if (Array.isArray(data)) { data.forEach(student => { var option = document.createElement("option"); option.value = student.id; option.text = `${student.firstName} ${student.lastName}`; studentSelect.add(option); }); } else { console.error("Invalid data format. Expected an array."); } }) .catch(error => { console.error('Error fetching students:', error); }); } } </script>
-
Thanks @Barand That solved the sql problem, but when I incorporated it, it is like I am having json issue, it is not being populated. Here is my class_year.php to populate the list... <?php include 'database.php'; $year = $_GET['year'] ?? null; if ($year === null) { http_response_code(400); echo json_encode(['error' => 'Missing required parameter: year']); exit(); } $sql = "SELECT s.id, s.firstname, s.lastname, c.classname FROM class c JOIN student_class sc ON sc.classid = c.id AND sc.semesterid = 1 JOIN student s ON sc.studentid = s.id WHERE c.year = ? ORDER BY s.lastname"; $stmt = getDatabaseConnection()->prepare($sql); $stmt->bind_param("i", $year); $stmt->execute(); $result = $stmt->get_result(); if (!$result) { http_response_code(500); // Internal Server Error echo json_encode(['error' => 'Database error']); exit(); } $students = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); getDatabaseConnection()->close(); // Set response headers to indicate JSON content header('Content-Type: application/json'); // Output JSON response echo json_encode($students); ?> And here is my json <script> function updateStudentNames() { var selectedYear = document.getElementById("year").value; console.log("Selected Year:", selectedYear); var studentSelect = document.getElementById("student"); // Clear previous options studentSelect.innerHTML = ""; // Fetch and add new options based on the selected year if (selectedYear !== "") { fetch(`class_year.php?year=${selectedYear}`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log("Fetched Data:", data); if (Array.isArray(data)) { data.forEach(student => { var option = document.createElement("option"); option.value = student.id; option.text = `${student.firstName} ${student.lastName}`; studentSelect.add(option); }); } else { console.error("Invalid data format. Expected an array."); } }) .catch(error => { console.error('Error fetching students:', error); }); } } </script> Html form <label for="semester" class="form-label">Current Session/Term</label> <input type="text" class="form-control rounded-0" name="semester" id="semester" required="required" value="<?= $current_term ?>" readonly> </div> <!-- test --> <label for="year" class="form-label">Year <select class="form-control rounded-0" name="year" id="year" required="required" onchange="updateStudentNames()"> <option value=''>- select year -</option> <option value='7'>Year 7</option> <option value='8'>Year 8</option> <option value='9'>Year 9</option> <option value='10'>Year 10</option> <option value='11'>Year 11</option> <option value='12'>Year 12</option> </select> </label> <label for="student" class="form-label">Student <select class="form-control rounded-0" name="student" id="student" required="required"> <!-- student name options for selected year will be dynamically populated here --> </select> </label>
-
It is high time I tipped my cap to phpfreaks, small but mighty. Phpfreaks may be small in population, but the sense and knowledge derived from it are immeasurable. Here, you find gurus who are always ready to solve our problems. Since I joined this forum, I no longer bother flipping to any other place to get my problems solved because phpfreaks is competent. Please do not relent, and keep up the good work. Regards to you all.
-
- 1
-
-
From the image attached, I have Session/Term not editable, it is the current session/term which is automatic. I have 5 classes and each class have like three or more arms such as 7A, 7B, 7C, 8A, 8B, 8C, etc In my html form for the Student class, I have Class 7, 8, etc which means 7A, 7B, 7C are under 7. I don't know how to go do it such that when Class is selected, it will populate the Student Name with the students in both arms of Class 7 (i.e all the students in 7A, 7B, 7C, etc). What I was using is to fetch all the names from the students table. Here is the html form: <label for="customer" class="form-label">Year <select class="form-control rounded-0" name="year" id="year" required="required"> <option value=''>- select year -</option> <option value='7'>Year 7</option> <option value='8'>Year 8</option> <option value='9'>Year 9</option> <option value='10'>Year 10</option> <option value='11'>Year 11</option> <option value='12'>Year 12</option> </select></label> </select> <label>Student <select class="form-control rounded-0" name="student" id="student" required="required"> <!-- student name options for selected year --> </select></label> Here are the tables -- Table structure for table `class` -- CREATE TABLE `class` ( `id` int(11) NOT NULL, `classname` varchar(45) DEFAULT NULL, `levelid` int(11) NOT NULL, `year` tinyint(4) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- Table structure for table `student_class` -- CREATE TABLE `student_class` ( `id` bigint(20) NOT NULL, `studentid` int(11) DEFAULT NULL, `semesterid` int(11) DEFAULT NULL, `classid` int(11) DEFAULT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- Table structure for table `student` -- CREATE TABLE `student` ( `id` int(11) NOT NULL, `firstName` varchar(50) NOT NULL, `lastName` varchar(50) NOT NULL, `otherName` varchar(50) NOT NULL, `matricNo` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `levelId` int(11) DEFAULT NULL, `DOB` date NOT NULL, `Phone` varchar(15) NOT NULL, `Email` varchar(100) NOT NULL, `image` varchar(255) DEFAULT NULL, `dateCreated` date NOT NULL, `leavingdate` date DEFAULT NULL, `login_disabled` tinyint(4) NOT NULL DEFAULT 0, `last_login` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
Graph showing comparative analysis of students class performance.
Olumide replied to Olumide's topic in PHP Coding Help
Thank you @Barand for your brilliant contribution and experienced contribution. -
Graph showing comparative analysis of students class performance.
Olumide replied to Olumide's topic in PHP Coding Help
Thank you @Barand I will run the query when I am on PC, currently on phone. -
Graph showing comparative analysis of students class performance.
Olumide replied to Olumide's topic in PHP Coding Help
Thanks for the clarification, but if I may ask, why is the graph not capturing the same class average in the result table and for the class average as you stated above, consider a situation whereby there are 20 students in a class and 16 out of the 20 students took Biology, will the class average still be total scores attained by all students divided by the number of students or divided by the number of students who took the subject? Thanks