0

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");
        }
    })

});
Nagusameta
  • 109
  • 8
  • 1
    you both insert a run paralelel, you need fiirst to wait for the new id and then insert the second – nbk Oct 19 '21 at 15:08
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Arif Khan Oct 19 '21 at 15:17

0 Answers0