Я пытаюсь удалить запись из базы данных, используя javascript mysql API. Я создал таблицу, где я перечислил свои записи из базы данных. Я добавил кнопку удаления и кнопку просмотра сведений. Теперь, когда я нажимаю кнопку удаления. Кнопка удаления удаляет последнюю строку, а не ту, в которой есть кнопка, на которой я нажал. Моя кнопка просмотра информации работала нормально до сих пор, она делает то же самое. Он просматривает информацию о последней строке, а не о той строке, которая содержит кнопку просмотра. Это начало происходить, когда я добавил код кнопки удаления. Код ниже. Пожалуйста, помогите мне понять, что происходит.
HTML Код. Я отредактировал и добавил код html. Типичная строка ниже.
<tr class="record" id="record153">
<td>John Doe</td>
<td>11p</td>
<td>10</td>
<td>Cotton</td>
<td><p>Compound D: ranging from 464.29kg to 535.71kg.<br> Ammonium nitrate: ranging from 223.88kg to 253.73kg.<br> Potasium nitrate: ranging from 0.00kg to 0.00kg.</p></td>
<td><button>View Detail</button><button>Delete</button></td>
</tr>
Javascript код
var historicalContent = document.querySelector('.historical-data');
window.views.peek().style.display = "none";
historicalContent.style.display = 'block';
var backButton = document.querySelector('#back');
backButton.style.display = 'block';
var dashboard = document.querySelector("#dashboard");
window.views.push(dashboard);
window.views.push(historicalContent);
var table = document.querySelector('.table-container table');
let sql = `SELECT * FROM lab_results`;
let labResultsCollection;
//fire
connection.query(sql, function (err, results, fields) {
if (err) throw err;
else {
labResultsCollection = results;
console.log(results);
for (result of results) {
let record = document.createElement('tr');
record.className = 'record';
record.id = 'record' + result.id;
let farmerName = document.createElement('td');
farmerName.innerText = result.name;
let reference = document.createElement('td');
reference.innerText = result.ref;
let labNumber = document.createElement('td');
labNumber.innerText = result.lab_number;
let recommendations = document.createElement('td');
let cropName = document.createElement('td');
connection.query(`SELECT crop_id FROM crop_has_lab_results WHERE lab_results_id = ${result.id}`,
function (err, bresult, fields) {
if (err) {
throw err
} else {
//now get the id of the crop
crop_id = bresult[0].crop_id;
//fire
connection.query(`SELECT name FROM crop WHERE id = ${crop_id}`,
function (err, cresult, fields) {
if (err) throw err;
else {
cropName.innerText = cresult[0].name;
}
})
}
})
connection.query(`SELECT recommendation_id FROM lab_results_has_recommendation WHERE lab_results_id = ${result.id}`,
function (err, bresult, fields) {
if (err) {
throw err
} else {
//now get the id of the crop
if (bresult.length > 0) {
console.log(bresult);
recommendation_id = bresult[0].recommendation_id;
//fire
connection.query(`SELECT text1,text2,text3 FROM recommendation WHERE id = ${recommendation_id}`,
function (err, cresult, fields) {
if (err) throw err;
else {
let str = `<p>${cresult[0].text1}.<br/> ${cresult[0].text2}.<br/> ${cresult[0].text3}.</p>`;
recommendations.innerHTML = str;
}
})
}
}
})
record.appendChild(farmerName);
record.appendChild(reference);
record.appendChild(labNumber);
record.appendChild(cropName);
record.appendChild(recommendations);
let actions = document.createElement('td')
let viewDetail = document.createElement('button');
viewDetail.innerText = 'View Detail';
let deleteRecord = document.createElement('button');
deleteRecord.innerText = 'Delete';
actions.appendChild(viewDetail);
actions.appendChild(deleteRecord);
record.appendChild(actions);
deleteRecord.addEventListener('click', function () {
let xmysql = `DELETE FROM lab_results_has_recommendation WHERE lab_results_id = ${result.id}`;
let xmysql2 = `DELETE FROM crop_has_lab_results WHERE lab_results_id = ${result.id}`;
let xmysql3 = `DELETE FROM lab_results WHERE id = ${result.id}`;
console.log(xmysql, xmysql2, xmysql3);
connection.query(xmysql, function (err, bresult, fields) {
if (err) throw err;
else {
connection.query(xmysql2, function (err, cresult, fields) {
if (err) throw err;
else {
connection.query(xmysql3, function (err, dresult, fields) {
if (err) throw err;
else {
let record = document.getElementById(`record${result.id}`);
console.log("Id of the removed", result.id);
record.remove();
}
})
}
})
}
})
})
viewDetail.addEventListener('click', function () {
var detailPanel = document.querySelector('#detail-pane');
window.views.peek().style.display = 'none';
detailPanel.style.display = 'block';
detailPanel.innerHTML = '';
window.views.push(detailPanel);
let id = result.id;
let mysql = `SELECT * FROM lab_results WHERE id = ${id}`
connection.query(mysql, function (err, mresult, fields) {
if (err) {
throw err;
} else {
let myresult = mresult[0];
var name = document.createElement('h3');
name.innerText = myresult.name;
detailPanel.appendChild(name);
var lab_number = document.createElement('p');
lab_number.innerText = `Lab number: ${myresult.lab_number}`;
detailPanel.appendChild(lab_number);
var ref = document.createElement('p')
ref.innerText = `Reference: ${myresult.ref}`;
detailPanel.appendChild(ref);
var color = document.createElement('p');
color.innerText = `Color: ${myresult.color}`;
detailPanel.appendChild(color);
var texture = document.createElement('p');
texture.innerText = `Texture: ${myresult.texture}`;
detailPanel.appendChild(texture);
var pH = document.createElement('p');
pH.innerText = `pH: ${myresult.pH}`;
detailPanel.appendChild(pH);
var free_carbonate = document.createElement('p');
free_carbonate.innerText = `Free carbonate: ${myresult.free_carbonate}`;
detailPanel.appendChild(free_carbonate);
var conductivity = document.createElement('p');
conductivity.innerText = `Conductivity: ${myresult.conductivity}`;
detailPanel.appendChild(conductivity);
var nitrogen = document.createElement('p');
nitrogen.innerText = `Initial nitrogen ${myresult.nitrogen}`;
detailPanel.appendChild(nitrogen);
var nitrogen_after = document.createElement('p');
nitrogen_after.innerText = `Nitrogen after incubation ${myresult.m_nitrogen_init}`;
detailPanel.appendChild(nitrogen_after);
var phosphorus = document.createElement('p');
phosphorus.innerText = `Phosphorus: ${myresult.phosphorus}`;
detailPanel.appendChild(phosphorus);
var potasium = document.createElement('p');
potasium.innerText = `Potasium: ${myresult.potasium}`;
detailPanel.appendChild(potasium);
var calcium = document.createElement('p');
calcium.innerText = `Calcium: ${myresult.calcium}`;
detailPanel.appendChild(calcium);
var magnesium = document.createElement('p');
magnesium.innerText = `Magnesium: ${myresult.magnesium}`;
detailPanel.appendChild(magnesium);
var total_bases = document.createElement('p');
total_bases.innerText = `Total bases: ${myresult.total_bases}`;
detailPanel.appendChild(total_bases);
let mysql2 = `SELECT * FROM lab_results_has_recommendation WHERE lab_results_id =
${myresult.id}`;
connection.query(mysql2, function (erra, mresult2, fields) {
if (err) throw err;
else {
let myresult2 = mresult2[0];
let mysql3 = `SELECT * FROM recommendation WHERE id = ${myresult2.recommendation_id}`;
connection.query(mysql3, function (err, mresult3, fields) {
if (err) throw err;
else {
let myresult3 = mresult3[0];
let divider = document.createElement('hr');
divider.width = '100%';
detailPanel.appendChild(divider);
let recommendationView = document.createElement('div');
let recommendationHeading = document.createElement('h4');
recommendationHeading.innerText = 'Recommendation';
recommendationView.appendChild(recommendationHeading);
var nitrogen2 = document.createElement('p');
nitrogen2.innerText = `Nitrogen: from ${myresult3.nitrogen} `;
recommendationView.appendChild(nitrogen2);
var phosphorus2 = document.createElement('p');
phosphorus2.innerText = `Phosphorus: from ${myresult3.phosphorus}`;
recommendationView.appendChild(phosphorus2);
var potasium2 = document.createElement('p');
potasium2.innerText = `Potasium: from ${myresult3.potasium}`;
recommendationView.appendChild(potasium2);
var lime = document.createElement('p');
lime.innerText = `Lime: from ${myresult3.lime}`;
recommendationView.appendChild(lime);
var text1 = document.createElement('p');
var text2 = document.createElement('p');
var text3 = document.createElement('p');
text1.innerText = myresult3.text1;
text2.innerText = myresult3.text2;
text3.innerText = myresult3.text3;
recommendationView.appendChild(text1);
recommendationView.appendChild(text2);
recommendationView.appendChild(text3);
detailPanel.appendChild(recommendationView);
}
})
}
})
}
})
})
table.appendChild(record);