Mam formularz jak poniżej, który wyświetla mi pozycje dokumentu WZ pobranego z bazy MSSQL.
Wyświetlane są pozycje jedna za drugą, tzn. Najpierw pierwsza, potem druga itd...
Jest prosta logika, pusty nie uzupełniony formularz - nie ma żadnego podświetlenia, gdy uzupełnię wartość w polu CHECK i jest zgodna z polem ILOŚĆ - całość zmienia się na zielono i przechodzić ma do następnej pozycji. Gdy wartości się różnią to formularz zmienia się na czerwono - ma nie pozwalać na zapis danych do bazy póki ilość nie będzie zgodna.
Uzupełniam pole CHECK i daję zapisz, powinno się zapisywać do bazy MySQL za każdym razem i to się dzieje, ale...
gdy przechodzę na druga pozycję to podświetla na czerwono jakby sprawdzał pole ILOŚĆ z poprzednim wpisem do pola CHECK.
a jeżeli pole ILOŚĆ jest takie same jak pole CHECK w poprzednim wpisie to blokuje mi możliwość wpisania. Trochę pokręcone tłumaczenie ale może z kodu da się zrozumieć.
Proszę o pomoc jak to ogarnąć żeby po przejściu do następnej pozycji nie brał pod uwagę ilości z poprzedniego wpisu. Aha, jeszcze jedno, wyświetla w kółko ten same pozycje w kółko - nie chce zakończyć na ostatniej pozycji
Poniżej mój kod i, oraz skrypty:
<?php
if (!isset($_SESSION['user_name'])) { header("Location: index.php"); }
ini_set('display_startup_errors', 1
);
require 'db-connect.php';
require 'mysql-connect.php';
$documentNumber = $_GET['doc'] ?? '';
if (!isset($_SESSION['last_document']) || $_SESSION['last_document'] !== $documentNumber) { $_SESSION['current_position'] = 0;
$_SESSION['last_document'] = $documentNumber;
}
$operationDate = '';
if (!isset($_SESSION['current_position'])) { $_SESSION['current_position'] = 0;
}
$currentPosition = $_SESSION['current_position'];
$sql = "SELECT * FROM DB_NAME WHERE WZ_NR = ?";
$params = array($documentNumber); $stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
}
$positions = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$positions[] = $row;
}
$totalPositions = count($positions);
if ($totalPositions == 0) {
echo "<p>Nie znalezono pozycji dla dokumentu.</p>"; }
$currentRow = $positions[$currentPosition];
$positionNumber = $currentRow['lp'];
if (isset($_POST['save'])) { $checkValue = floatval($_POST['check'][$currentPosition] ?? 0
); $quantity = floatval($_POST['quantity'][$currentPosition] ?? 0
); $productShortcut = $_POST['productShortcut'][$currentPosition] ?? '';
$description = $_POST['description'][$currentPosition] ?? '';
$userName = $_SESSION['user_name'];
$sqlInsert = "INSERT INTO wz_records (document_number, operation_date, product_shortcut, description, quantity, check_value, save_date, position_number, user_name)
VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?)
ON DUPLICATE KEY UPDATE check_value = VALUES(check_value), save_date = NOW()";
$stmtInsert = $mysqli->prepare($sqlInsert);
if ($stmtInsert) {
$stmtInsert->bind_param("ssssddss", $documentNumber, $operationDate, $productShortcut, $description, $quantity, $checkValue, $positionNumber, $userName);
$stmtInsert->execute();
$stmtInsert->close();
}
$_SESSION['current_position']++;
if ($_SESSION['current_position'] >= $totalPositions) {
echo "<script>alert('To jest ostatnia pozycja.');</script>"; $_SESSION['current_position'] = 0;
}
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pozycje dokumentu</title>
<link rel="stylesheet" href="style.css">
<script src="scripts.js" defer></script>
</head>
<body>
<div class="container">
<div class="back-button">
<button onclick="window.location.href='index.php?date=
<?php echo htmlspecialchars($operationDate); ?>'">Powrót</button>
</div>
<div id="searchContainer">
<input type="text" id="searchField" placeholder="Wyszukaj EAN lub KODTW" onkeydown="checkEnter(event)">
</div>
<form method="POST" action="details.php?doc=
<?php echo urlencode($documentNumber); ?>" id="detailsForm">
<table id="dataTable">
<?php
$quantity = floatval($currentRow['QUANTITY'] ?? 0
);
$sqlCheck = "SELECT check_value FROM wz_records WHERE document_number = ? AND position_number = ?";
$stmtCheck = $mysqli->prepare($sqlCheck);
$stmtCheck->bind_param("si", $documentNumber, $positionNumber);
$stmtCheck->execute();
$stmtCheck->bind_result($savedCheckValue);
$stmtCheck->fetch();
$stmtCheck->close();
$checkValue = floatval($savedCheckValue ??
''); $isDisabled = ($checkValue !== '' && $checkValue == $quantity) ? 'disabled' : '';
$rowClass = ($checkValue !== '' && $checkValue == $quantity) ? 'success' : ($checkValue !== '' ? 'error' : '');
echo "<tr class='$rowClass'>"; echo "<th>EAN</th><td>$EAN</td>"; echo "<tr class='$rowClass'>"; echo "<th>KOD TW</th><td>$productShortcut</td>"; echo "<tr class='$rowClass'>"; echo "<th>OPIS</th><td>$description</td>"; echo "<tr class='$rowClass'>"; echo "<th>ILOŚĆ</th><td>$quantity</td>"; echo "<tr class='$rowClass'>"; echo "<th>CHECK</th><td><input type='number' name='check[$currentPosition]' value='' $isDisabled required></td>"; echo "<input type='hidden' name='quantity[$currentPosition]' value='$quantity'>"; echo "<input type='hidden' name='productShortcut[$currentPosition]' value='$productShortcut'>"; echo "<input type='hidden' name='description[$currentPosition]' value='$description'>"; ?>
</table>
<input type="submit" name="save" value="Save">
</form>
</div>
</body>
</html>
function checkEnter(event) {
if (event.key === "Enter") {
event.preventDefault();
let searchValue = document.getElementById('searchField').value.trim().toUpperCase();
if (searchValue !== '') {
let rows = document.querySelectorAll('#dataTable tr');
let found = false;
let firstMatch = null;
rows.forEach(row => {
let ean = row.getAttribute('data-ean') ? row.getAttribute('data-ean').toUpperCase() : '';
let kodtw = row.getAttribute('data-kodtw') ? row.getAttribute('data-kodtw').toUpperCase() : '';
if (ean.includes(searchValue) || kodtw.includes(searchValue)) {
row.classList.add('highlight');
if (!found) {
let checkInput = row.querySelector('input[type="number"]');
if (checkInput) {
checkInput.focus();
found = true;
}
}
} else {
row.classList.remove('highlight');
}
});
if (!found) {
alert('Nie znaleziono żadnych pasujących pozycji.');
let searchField = document.getElementById('searchField');
searchField.focus();
searchField.value = '';
}
}
}
}
document.getElementById('detailsForm').addEventListener('keydown', function (event) {
if (event.key === "Enter") {
event.preventDefault();
let activeElement = document.activeElement;
if (activeElement.tagName.toLowerCase() === 'input' && activeElement.type === 'number') {
handleEnter(event, activeElement);
}
}
});
function handleEnter(event, element) {
let row = element.closest('tr');
let quantity = parseFloat(row.querySelector('input[name^="quantity"]').value);
let checkValue = parseFloat(element.value);
if (checkValue === quantity) {
row.classList.remove('error');
row.classList.add('success');
element.setAttribute('readonly', true);
goToNextPosition();
} else {
row.classList.remove('success');
row.classList.add('error');
alert('Ilość nie zgadza się! Popraw dane.');
}
}
function goToNextPosition() {
let rows = document.querySelectorAll('#dataTable tr');
let currentRow = Array.from(rows).find(row => row.classList.contains('success'));
if (currentRow) {
let nextRow = currentRow.nextElementSibling;
if (nextRow) {
let nextInput = nextRow.querySelector('input[name^="check"]');
if (nextInput) {
nextInput.focus();
}
} else {
alert('Osiągnięto ostatnią pozycję.');
}
}
}