编程新手求助:如何获取id为nilai的输入框值并插入MySQL
Hey there! No worries at all—we all start somewhere, and your question makes perfect sense even with limited English 😊 Let's break this down step by step, because first there's a small issue with your current code we need to fix, then we'll handle getting the values and saving them to the database.
First: Fix the Duplicate ID Problem
Right now, you're generating multiple inputs with the same id="nilai"—but in HTML, IDs must be unique! This will cause problems when you try to get their values later. Let's change that to a class instead, and also add a data attribute to link each input to the corresponding student's nis (so we know which score belongs to which student):
// Modified dynamic HTML generation code html += '<tr>'; html += '<td class="indi" align="center">' + row.nis + '</td>'; html += '<td class="indi">' + row.nama_siswa + '</td>'; html += '<td>'; // Use class instead of id, and add data-nis to store the student's NIS html += '<input class="nilai" type="text" placeholder="nilai" data-nis="' + row.nis + '"/>'; html += '</td>';
Step 1: Collect All Input Values
Once your table is generated, you can get all the input values along with their associated student NIS using JavaScript. Let's write a function to collect this data:
function collectNilai() { // Get all input elements with class "nilai" const nilaiInputs = document.querySelectorAll('.nilai'); const nilaiData = []; // Loop through each input nilaiInputs.forEach(input => { const nis = input.dataset.nis; // Get the student's NIS from data attribute const nilai = input.value.trim(); // Get the input value (trim whitespace) // Only add to the array if the value isn't empty if (nilai) { nilaiData.push({ nis: nis, nilai: nilai }); } }); return nilaiData; }
Step 2: Send Data to Backend (Using Fetch API)
Next, we need to send this collected data to a backend script (we'll use PHP as an example) that will insert it into MySQL. Let's create a function to handle the submission:
async function saveNilaiToDatabase() { const nilaiData = collectNilai(); if (nilaiData.length === 0) { alert('No scores to save!'); return; } try { const response = await fetch('save_nilai.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(nilaiData), }); const result = await response.json(); if (result.success) { alert('Scores saved successfully!'); } else { alert('Error saving scores: ' + result.message); } } catch (error) { alert('Network error: ' + error.message); } }
You can call this function when a button is clicked, for example:
<button onclick="saveNilaiToDatabase()">Save All Scores</button>
Step 3: Backend Script (save_nilai.php)
Now let's write the PHP script that receives the data and inserts it into MySQL. Important: Always use prepared statements to prevent SQL injection!
<?php // Database configuration (replace with your own) $host = 'localhost'; $dbname = 'your_database_name'; $username = 'your_username'; $password = 'your_password'; try { // Connect to MySQL using PDO $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Get the JSON data from the request $data = json_decode(file_get_contents('php://input'), true); if (!$data || !is_array($data)) { throw new Exception('Invalid data received'); } // Prepare the insert statement $stmt = $pdo->prepare("INSERT INTO your_table_name (nis, nilai) VALUES (:nis, :nilai)"); // Loop through each data entry and execute the statement foreach ($data as $entry) { $stmt->execute([ ':nis' => $entry['nis'], ':nilai' => $entry['nilai'] ]); } // Return success response echo json_encode(['success' => true, 'message' => 'All scores inserted']); } catch (Exception $e) { // Return error response echo json_encode(['success' => false, 'message' => $e->getMessage()]); } ?>
Important Notes
- Replace
your_database_name,your_username,your_password, andyour_table_namewith your actual MySQL details. - Make sure your MySQL table has columns
nis(to store the student ID) andnilai(to store the score). - Always validate and sanitize user input (we added
trim()in JavaScript, but you can add more checks in PHP if needed).
内容的提问来源于stack exchange,提问作者Isk

