When a contact form is submitted, by the database design I was provided with, the customer e-mail and name should go into customerinfo
table, while their message goes into questionrecord
table. The foreign key in questionrecord
table references the CustomerID in customerinfo
table, which is an Auto-incrementing Primary key. In this post , I found that the last inserted ID can be retrieved on the results variable and I found it viable to be inserted as the foreign key value for the row to be inserted in questionrecord
.
I then wrote the code below in hopes of inserting to customerinfo
table first, then retrieve the last inserted id and insert it as the foreign key to the new questionrecord
record.
But it leads to the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.
I assume I cannot call query() twice in the same Express route? How can I perform something similar?
I had thought of redirecting the post request to another route which handles inserting into questionrecord
table separately but I have no way to send the value of the last inserted ID along with the redirect.
app.post('/inquiryPost', (req, res) => {
let newCustomer = {CustomerEmail: req.body.inqEmail, CustomerName: req.body.fullName};
let sql = 'INSERT INTO customerinfo SET ?';
let lastInsertId;
console.log(newCustomer)
con.query(sql, newCustomer, (err, result) => {
if (!err) {
lastInsertID = result.insertId;
} else {
res.send("failed to insert into customerinfo table");
}
})
let newQuestion = {CustomerID: lastInsertId, CustomerConcern: req.body.contactMsg};
let sql2 = 'INSERT INTO questionrecord SET ?';
con.query(sql2, newQuestion, (err, result) => {
if (!err) {
res.sendFile("../SE-Metro-Q/contact.html")
} else {
res.send("failed to insert into customerinfo table");
}
})
});