theloftstore/public/userarea/save_edited_row.php

81 lines
2.4 KiB
PHP

<?php
include('include/headscript.php');
header('Content-Type: application/json');
$response = ['success' => false, 'message' => ''];
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['iddatadb'])) {
throw new Exception('Richiesta non valida');
}
$iddatadb = intval($_POST['iddatadb']);
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$data = $_POST;
$details = [];
// 1. POST-დან ამოვიღოთ მხოლოდ details
foreach ($data as $key => $value) {
if (preg_match('/^details(\d+)field_value$/', $key, $matches)) {
$id = $matches[1];
$details[$id] = $value;
}
}
// 2. DB-დან წამოვიღოთ არსებული მნიშვნელობები
$stmt = $pdo->prepare("SELECT mapping_id, field_value FROM import_data_details WHERE id = ?");
$stmt->execute([$iddatadb]);
$currentValues = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$currentValues[$row['mapping_id']] = $row['field_value'];
}
// 3. შევადაროთ POST-ს და DB-ს
$changed = [];
foreach ($details as $id => $newValue) {
$oldValue = $currentValues[$id] ?? null;
if ($oldValue !== $newValue) {
$changed[$id] = [
'old' => $oldValue,
'new' => $newValue
];
}
}
// 4. თუ არის ცვლილებები → UPDATE
if (!empty($changed)) {
$updateStmt = $pdo->prepare("
UPDATE import_data_details
SET field_value = :newValue
WHERE id = :iddatadb AND mapping_id = :mappingId
");
foreach ($changed as $mappingId => $values) {
$updateStmt->execute([
':newValue' => $values['new'],
':iddatadb' => $iddatadb,
':mappingId' => $mappingId
]);
}
$response['success'] = true;
$response['message'] = "Updated successfully";
$response['changed'] = $changed; // Debug / optional
} else {
$response['success'] = true;
$response['message'] = "No changes found";
}
} catch (Exception $e) {
$response['success'] = false;
$response['message'] = $e->getMessage();
error_log("Errore in save_edited_row.php: " . $e->getMessage());
}
echo json_encode($response);
exit;