Sto affrontando un problema nel tentativo di aggiornare i record nel mio database da una tabella HTML utilizzando JavaScript e PHP. Ho creato un'applicazione web in cui carico dati da un database MySQL in una tabella HTML, consento agli utenti di modificare le celle della tabella e poi salvare le modifiche nel database. Tuttavia, gli aggiornamenti non vengono riflessi nel database. Ecco una descrizione del mio codice:
Index.html
codice:
<!DOCTYPE html><html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
#search {
margin-bottom: 20px;
}
.input-form {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.input-form input[type="text"],
.input-form input[type="date"] {
border: none;
border-radius: 5px;
padding: 10px;
font-size: 16px;
width: 200px;
}
/* Aggiungi questa classe per evidenziare le celle modificate */
.editable {
background-color: lightblue;
}
</style>
</head>
<body>
<div class="input-form">
<form action="insert.php" method="post">
<input type="text" name="nome" placeholder="Nome">
<input type="text" name="attivo" placeholder="1 o 2">
<input type="date" name="scadenza">
<input type="text" name="seriale" placeholder="Seriale telefono">
<input type="submit" value="Invia">
</form>
</div>
<input type="text" id="search" placeholder="Cerca per nome...">
<table id="myTable">
<tr>
<th>Nome</th>
<th>Attivo</th>
<th>Scadenza</th>
<th>Seriale</th>
</tr>
<!-- I dati del database verranno inseriti qui -->
</table>
<button id="saveChanges">Salva modifiche</button>
<script src="loadData.js"></script>
</body>
</html>
Insert.php
codice:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database name";
// Crea la connessione
$conn = new mysqli($servername, $username, $password, $dbname);
// Controlla la connessione
if ($conn->connect_error) {
die("Connessione fallita: " . $conn->connect_error);
}
$nome = $_POST['nome'];
$attivo = $_POST['attivo'];
$scadenza = $_POST['scadenza'];
$seriale = $_POST['seriale'];
// Scrivi la query SQL per inserire i dati nella tabella, senza specificare un valore per "id"
$sql = "INSERT INTO Seriali (Nome, Attivo, Scadenza, Seriale) VALUES ('$nome', '$attivo', '$scadenza', '$seriale')";
// Esegui la query e controlla se ha avuto successo
if ($conn->query($sql) === TRUE) {
echo "Nuovo record inserito con successo";
} else {
echo "Errore nell'inserire il record: " . $conn->error;
}
$conn->close();
?>
loadData.js
codice:
document.addEventListener("DOMContentLoaded", function () {
// Funzione per caricare i dati dalla tabella
function loadData() {
fetch('loadData.php')
.then(response => response.json())
.then(data => {
const table = document.getElementById("myTable").querySelector("tbody");
data.forEach(item => {
const row = table.insertRow(-1);
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
const cell4 = row.insertCell(3);
cell1.contentEditable = "true";
cell2.contentEditable = "true";
cell3.contentEditable = "true";
cell4.contentEditable = "true";
cell1.innerHTML = item.Nome;
cell2.innerHTML = item.Attivo;
cell3.innerHTML = item.Scadenza;
cell4.innerHTML = item.Seriale;
row.id = item.id; // Assicurati che il tuo database abbia una colonna 'id'
});
})
.catch(error => console.error('Errore:', error));
}
// Carica i dati iniziali
loadData();
// Aggiungi un gestore di eventi per il pulsante "Salva modifiche"
document.getElementById('saveChanges').addEventListener('click', function () {
const table = document.getElementById("myTable").querySelector("tbody");
const rows = table.getElementsByTagName("tr");
// Inizia il loop da i = 1 per saltare la riga dell'intestazione
for (let i = 1; i < rows.length; i++) {
const cells = rows[i].getElementsByTagName("td");
const id = rows[i].id;
// Invia i dati delle celle modificate al tuo script PHP
const nome = cells[0].textContent;
const attivo = cells[1].textContent;
const scadenza = cells[2].textContent;
const seriale = cells[3].textContent;
// Crea un oggetto JSON con i dati delle celle
const data = {
'id': id,
'nome': nome,
'attivo': attivo,
'scadenza': scadenza,
'seriale': seriale
};
// Invia l'oggetto JSON al tuo script PHP usando il metodo 'POST'
fetch('update.php', {
method: 'POST', // Cambia il metodo da 'PUT' a 'POST'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Errore:', error));
}
});
// ...
});
loadData.php
codice:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database name";
// Crea la connessione
$conn = new mysqli($servername, $username, $password, $dbname);
// Controlla la connessione
if ($conn->connect_error) {
die("Connessione fallita: " . $conn->connect_error);
}
$sql = "SELECT Nome, Attivo, Scadenza, Seriale FROM Seriali ORDER BY Scadenza DESC";
$result = $conn->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
$conn->close();
?>
update.php
codice:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database name";
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get JSON data from the request body
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);
$id = $data['id'];
$nome = $data['nome'];
$attivo = $data['attivo'];
$scadenza = $data['scadenza'];
$seriale = $data['seriale'];
// Use a prepared statement to update the data in the table
$stmt = $conn->prepare("UPDATE Seriali SET Nome = ?, Attivo = ?, Scadenza = ?, Seriale = ? WHERE Id = ?");
$stmt->bind_param("ssssi", $nome, $attivo, $scadenza, $seriale, $id);
$response = array();
if ($stmt->execute()) {
$response['success'] = true;
$response['message'] = "Dati aggiornati con successo";
} else {
$response['success'] = false;
$response['message'] = "Errore nell'aggiornare i dati: " . $stmt->error;
error_log("Errore nell'aggiornare i dati: " . $stmt->error);
}
$stmt->close();
$conn->close();
// Return the JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>
Ho aggiunto una colonna "id" al mio database per identificare univocamente ciascun record. È necessaria questa colonna per l'aggiornamento dei record, e come dovrei usarla nel mio codice?
Ci sono potenziali problemi o errori nel mio codice che potrebbero impedire il salvataggio degli aggiornamenti nel database?
Spero che queste informazioni possano essere utili per risolvere il problema.
https://imgur.com/a/P0jKyPL questi sono due screenshot dalla dashboard php Myadmin