I have 2 different tables where the first table is used for retrieving the data to store in the second table, so for example, if there are 3 items in the first table, ill run a for loop 3 times to retrieve the information and storing it in the second table row by row, i also have to use a unique id for the primary key for the second table, so i have to run another mysql query to retrieve all the ID in the second table and add 1 to the id to generate a new ID, but the problem for me is that when i try to put a connection.query in another connection.query, the outer connection.query runs 3 time before running the inner connection.query, hence the items does not get stored and the id does not update, giving me a duplicate primary key error, i tried using functions but it doesnt help, here is
app.get('/submit-check', function (request, response) {
function insert(sql2) {
connection.query(sql2, function (err, result1) {
if (err) throw err;
});
}
function other(value, index) {
let sql = "SELECT * FROM ORDERS"
connection.query(sql, function (err, results) {
var id;
if (results.length == 0) {
id = 0
} else {
id = results[results.length - 1].orderID;
}
// for (let j = 0; j < results.length; j++) {
// list.push(results[j].orderID)
// }
// if (list.length == 0) {
// id = 0
// }
// else {
// var largest = 0;
// for (let i = 0; i <= list.length; i++) {
// if (parseInt(list[i]) > largest) {
// var largest = parseInt(list[i]);
// }
// }
// id = largest + 1
// }
id = id + 1;
var add = request.query.state + " " + request.query.address + " " + request.query.Unumber + " " + request.query.zip
var custID = value[index].custID
var bookID = value[index].bookID
var Email = request.query.email
var CardName = request.query.cardname
var CardNumber = request.query.cardnumber
var ExDate = request.query.expmonth + "/" + request.query.expyear
var CVV = request.query.cvv
var qty = 1
var sql2 = "INSERT INTO orders (orderID,custID, bookID, QTY, CardName, CardNumber, ExDate, CVV, Email, Address, createdAt, updatedAt) VALUES('" + id + "','" + custID + "', '" + bookID + "', '" + qty + "', '" + CardName + "', '" + CardNumber + "', '" + ExDate + "', '" + CVV + "', '" + Email + "', '" + add + "', CURDATE(), CURDATE() )"
insert(sql2)
})
}
function setValue(value) {
for (let index = 0; index < value.length; index++) {
other(value, index)
}
}
let sql3 = "SELECT * FROM carts"
var cart_db;
connection.query(sql3, function (err, result) {
cart_db = result
setValue(cart_db)
})
// console.log(cart_db)
response.render("aftercheck", { attributes: request.query, cardno: "****-****-****" + request.query.cardnumber.slice(-5,) });
})
thank you in advance
SELECT * FROM tablequeries with noWHEREorORDERclauses? There are no guarantees you'd get what you want.